Add property with - in name - html

In MVc I am using Html.TextboxFor() control
I have input type control as below.
<input id="phoneNumber" type="text" class="phoneNumber form-control" value="#actorPhone.PhoneNumber" data-phoneType ="#actorPhone.PhoneTypeTd" data-actorId ="#Model.ActorId" maxlength="30"/>
I want to change this intput control to MVC
#Html.TextBoxFor(m=>m.phoneNumber,new {#class = "phoneNumber", maxlength = "30"})
How I can add data-phoneType and data-actorId properties to the html control, as - is not allowed in the properties of HTML Attribute.

use an underscore _
the Razor engine is smart enough to render the underscore within the property name to the corresponding dash sign, resulting in your desired HTML5-like attributes
example:
#Html.TextBoxFor(m=>m.phoneNumber,
new {#class = "phoneNumber", maxlength = "30",
data_phoneType = YOUR_VALUE_HERE,
data-actorId=YOUR_VALUE_HERE })
and this should result in your desired output.
hope this helps :)

You can set an underscore instead and Razor will render it like a minus/dash:
#Html.TextBoxFor(m => m.phoneNumber,
new { data_phoneType = "phone type",
#class = "phoneNumber",
maxlength = "30"})

Use data_* attributes like
#Html.TextBoxFor(m=>m.phoneNumber,
new {
data_phoneType=actorPhone.PhoneTypeTd,
#class = "phoneNumber",
maxlength = "30"
})

Related

How can restrict two decimal places only in Input Number

How can I given restriction only to accept two decimal place or how can I format with only two decimal place . I tried with model RegularExpression(#"^\d+.\d{0,2}$" and I tried #step 01 and tabindex 7, still not working , we can give more than two numbers for decimal . Here is the code
#Html.TextBoxFor(m => m.attendanceLogList[i].NormalHrs, new
{
#class = "form-control input-sm emphrs",
#style = columnstyle,
#Value = Model.attendanceLogList[i].NormalHrs,
#type = "number",
#step = ".01",
onchange = "CalculateTotal(this);"
})
Assuming the onchange event CalculateTotal(this); is a javascript function. IMHO, applying the javascript as below into your Razor snippet, in the same way, should work, FYI.
function fixDecimal(e) {
return e.value = e.value.toString().match(/^\d+(?:\.\d{0,2})?/);
}
<input type="number" step="0.01" onkeyup="fixDecimal(this)" />

How to make #Html.TextBox hidden and of date type at the same time?

I need to hide textbox of type=date. Later I want to show this textbox again using some js. The issue is how I can use type=date and type=hidden at the same time in html helper? I can't add another 'type' attribute because an error shows up. The below is wrong:
#Html.TextBox("dateFrom", null, new { #type = "date", #type = "hidden", #class = "form-control datepicker"})
Is it possible to hide this datepicker using hidden attribute?

How to set programatically the Id, Name and Class atribute of a #Html.EditFor or #Html.TextBoxFor - MVC 4

I am trying to generate a unique label and and input text box for a partial view that is being used to render a list of user input rows.
By unique I mean that each input text box should have its unique html "id" and "name" so that when is submitted each input can be identified
In the View I have
#model UserDataModel
#{
var inpName = "benefName" + #Model.Row;
var inpAge = "benefAge" + #Model.Row;
}
#Html.LabelFor(x => x.Name, new { #class="labelhalf"})
#Html.EditorFor(x => x.Name, new { id = #inpName, htmlAttributes = new { #class = "form-control animated" } })
When the view is being render this is what I am seeing
<label class="labelhalf" for="Name">Nombre (Opcional)</label>
<input class="text-box single-line" id="Name" name="Name" type="text" value="">
As you can see the "name" and "id" attributes of the text input is "Name" and "Name" and is not using the value of the #inpName variable ("benefName1" for example)
Also I am trying to assign some CSS classes to that same input using "htmlAttributes"
I had previously tried this with this approach
<label form="FormStep_01" for=#inpName class="labelhalf">Nombre (Opcional)</label>
<input form="FormStep_01" id=#inpName class="form-control animated" pattern="^[_A-z0-9]{1,}$" type="text" placeholder="" required="">
...but the content of the input fields with this approach are not being submited and that is the reason I am trying to use the #Html.EditorFor
UPDATE
I am now using the TextBoxFor which takes the "id" and the "class" fine but not the "name" which is used in the submit
#Html.LabelFor(x => x.Name, new { #class = "labelhalf" })
#Html.TextBoxFor(x => x.Name, new { #id = #inpName, name = #inpName, #class = "form-control animated" })
Please let me know how to achieve this in MVC4
Issue 1 (Using EditorFor())
You cannot add html attributes using EditorFor() in MVC-4. This feature was not introduced until MVC-5.1, and then the correct usage is
#Html.EditorFor(m => m.SomeProperty, new { htmlAttributes = new { someAttribute = "someValue" }, })
Issue 2 (Using TextBoxFor())
You cannot change the value of the name attribute using new { name = "someValue" }. The MVC team built in a safe guard to prevent this because the whole purpose of using the HtmlHelper methods to generate form controls is to bind to your model properties, and doing this would cause binding to fail. While there is a workaround, if you do discover it, don't do it! As a side note - the following line of the private static MvcHtmlString InputHelper() method in the source code
tagBuilder.MergeAttribute("name", fullName, true);
is what prevents you overriding it.
Issue 3 (Manual html)
You not giving the inputs a name attribute. A form posts back a name/value pair based on the name and value attributes of successful controls, so if there is no name attribute, nothing will be sent to the controller.
Side note: If your manually generating html, there is no real need to add an id attribute unless your referring to that element in javascript or css.
Its unclear why your trying to create a input for something that does not appear to relate to your model, but if your trying to dynamically generate items for adding items to a collection property in your model, refer the answers here and here for some options which will allow you to bind to your model.

Input field set as 'Value=' instead of 'value='

I have a project written in C# MVC using Razor templates. On one of my pages I have several input fields that contain numeric values. The Razor code that sets the values of these input fields looks like this:
#Html.Editor(Model.DesignParams[i].ParamId,
new {
htmlAttributes = new
{
#Value = Model.DesignParams[i].DefaultValue,
#class = "form-control text-right",
#type = "text",
id = "_" + Model.DesignParams[i].ParamId,
uomid = Model.DesignParams[i].UOMId,
measureid = Model.DesignParams[i].MeasureId
}
})
The above code works fine using FireFox and Chrome and generates an input field that looks like this:
<input type="text" uomid="MBH" name="HeatOfRejection" measureid="HeatLoad"
id="_HeatOfRejection" class="form-control text-right text-box single-line"
value="5000.0">
But the same Razor code, identical #Model values viewed with IE generates this:
<input Value="5000" class="form-control text-right text-box single-line"
id="_HeatOfRejection" measureid="HeatLoad" name="HeatOfRejection"
type="text" uomid="MBH" value="" />
As you can see, there is a difference between the value= attribute generated for IE in that the value attribute that gets my actual value begins with an uppercase 'V' and the lowercase value is an empty string. I'm stumped on this...
Can anyone tell me why this is happening and possibly how to handle it?
This difference effects jQuery's ability to return the input's value with:
var value = $(inputfield).attr("value");
Maybe .val() will retrieve the input field value, but this is going to require a rewrite of core jQuery code that supports this page and others, so I wanted to ask if anyone can tell me why this 'Value=' gets created for IE only and if there is a way of overcoming the problem.
Update:
Changing #Value to #value (or just value) results in an empty value attribute in Firefox and IE:
<input type="text" value="" uomid="MBH" name="HeatOfRejection" measureid="HeatLoad"
id="_HeatOfRejection" class="form-control text-right text-box single-line">
As StuartLC points out, you are trying to get Html.Editor to do something it wasn't designed to do.
What happens when you pass a #value or #Value key to the htmlAttributes is that the rendering engine produces an attribute with that name in addition to the value attribute it's already generating:
<input type="text" name="n" value="something" value="somethingElse" />
or
<input type="text" name="n" value="something" Value="somethingElse" />
In both cases, you're giving the browser something bogus, so it can't be expected to exhibit predictable behavior.
As alluded above, Html.Editor has functionality to generate the value attribute based on the expression argument you pass to it. The problem is that you are using that incorrectly as well. The first argument to Html.Editor() needs to be an expression indicating the model property that the editor should be bound to. (e.g. the string value "DesignParams[0].ParamId") Nowadays, the preferred practice is to use the more modern EditorFor that takes a lambda function, as StuartLC showed in his post:
#Html.EditorFor(model => model.DesignParams[i].ParamId, ...)
You are "capitalising" the value html attribute. Change this to lower case...
#Value = Model.DesignParams[i].DefaultValue
as below ...
#value = Model.DesignParams[i].DefaultValue
IE is not the smartest of web browsers and there's definitely something wrong in the way Trident (they're parsing engine) validates elements' attributes as seen in these threads...
https://github.com/highslide-software/highcharts.com/issues/1978
Highcharts adds duplicate xmlns attribute to SVG element in IE
Also, as already noted somewhere else. What's the need for the Editor extension method? Isn't it simpler to just use TextBoxFor instead?
#Html.TextBoxFor(model => model.DesignParams[i].ParamId
, new
{
#class = "form-control text-right"
, uomid = Model.DesignParams[i].UOMId
, measureid = Model.DesignParams[i].MeasureId
})
Editor works with metadata. then you need to more about this,
http://aspadvice.com/blogs/kiran/archive/2009/11/29/Adding-html-attributes-support-for-Templates-2D00-ASP.Net-MVC-2.0-Beta_2D00_1.aspx
But the easiest way is go with
#model Namespace.ABCModel
#using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
#Html.TextBoxFor(model => model.DesignParams[i].ParamId, new { #class = "form-control text-right", uomid = Model.DesignParams[i].UOMId, measureid = Model.DesignParams[i].MeasureId })
}
You shouldn't be using invalid Html attributes in this way. Use the data- attributes in Html 5.
Also, your use of #Html.Editor(Model.DesignParams[i].ParamId (assuming ParamId is a string) deviates from the helper's purpose, which is to reflect the property with the given name off the Model, and use the value of this property as the Html value attribute on the input. (MVC will be looking for a property on the root model with whatever the value of ParamId is, which seems to silently fail FWR)
I would do the defaulting of Model.DesignParams[i].ParamId = Model.DesignParams[i].DefaultValue in the Controller beforehand, or in the DesignParams constructor.
#Html.EditorFor(m => m.DesignParams[0].ParamID,
new {
htmlAttributes = new
{
// Don't set value at all here - the value IS m.DesignParams[0].ParamID
#class = "form-control text-right",
#type = "text",
id = "_" + Model.DesignParams[i].ParamId,
data_uomid = Model.DesignParams[i].UOMId,
data_measureid = Model.DesignParams[i].MeasureId
}
Note that this will give the input name as DesignParams[0].ParamID, which would be needed to post the field back, if necessary.
Here's a Gist of some example code
(The underscore will be converted to a dash)
Use data() in jQuery to obtain these values:
var value = $(inputfield).data("uomid");

how to add maxlength for TextAreaFor in View using razor engine

I have a TextArea() control in my View implemented using Razor Engine.
#Html.TextArea("EventNature",new { style = "width: 200px; height: 100px;" })
How can i set the Maxlength attribute for this control?
is there any built in Attribute in RazorEngine or do i have to use scripts?
You can do it like:
#Html.TextArea("EventNature",new { maxlength=50, // or other value
style = "width: 200px; height: 100px;" })
Just be aware it's an HTML5 attribute
maxlength HTML5
The maximum number of characters (Unicode code points) that the user can enter. If it is not specified, the user can enter an unlimited number of characters.
MDN
Javascript(using jQuery) validation for HTML <5:
$('#EventNature').keypress(function(){
if (this.value.length >= 10) // allowing you to enter only 10 chars.
return false;
});​
DEMO
This also works for the TextAreaFor helper with more than one anonymous type in new
Confirmed to work fine in Visual Studio 2015 with MVC 5
#Html.TextAreaFor(model => model.Comments, 5, 500, new {maxlength=4000, #class = "form-control" })
You can also restrict the length of textbox, like this:
<textarea id="EventNature1" maxlength="10"></textarea>
OR
#Html.TexareaFor(m=>m.Name,new{#maxlength="10"})
<p>Customer Number: #Html.TextBox("SearchString1",null, new {maxlength = 6})
<input type="submit" value="Filter" /></p>
The above is an example that worked for me to restrict the maximum allowed characters to be entered. The tips that show up that you can arrow through when using a .Net environment are extremely helpful. (*note, this doesn't physically change the size of the text box)
"SearchString1" = String name ----- null = Object value ------ new {maxlength = 6} = object htmlAttributes
How can i set the Maxlength attribute for this control?
The maxlength attribute is not valid for the <textarea> element. That's not an ASP.NET MVC limitation. In the HTML specification this attribute is defined only for simple text input fields. If you want to limit the number of characters that a user could type in a textarea you could use javascript.