I have a model like:
public class MyModel {
public string Name {get; set;}
public DateTime StartDate {get; set;}
}
Then, in my Razor view, I have this:
@Html.EditorFor(x => x.StartDate, new { @class = "input datepicker" })
The outputted HTML however, looks like this:
<input class="text-box single-line" data-val="true"
data-val-required="The StartDate field is required." id="StartDate"
name="StartDate" type="text" value="01/01/0001 00:00:00">
It seems to be completely ignoring my @class
definition (as well as adding validation stuff of its' own)
Is there a way of making it render with my specified class?
Remember that the actual parameter is for additional view data, so what this does is essentially add the key ViewData ["htmlAttributes"] with the value set to the anonymous object that contains the class you want set. EditorFor, now, looks for this key and will add the appropriate HTML attributes in its default templates.
Simply put, the Html.EditorFor method allows the developer to retain control over the display of form elements by data type (ie. string, boolean, int…etc) or model attribute at a global level rather than at an individual view level.
Now, you can pass additonal HTML attributes to your custom editor templates, and since we kept the ViewData key name the same, it's seemless whether you end up using an custom editor editor template or one of the default editor templates.
Let's take an example with the string.cshtml editor template: @model string @Html.TextBox ("", ViewData.TemplateInfo.FormattedModelValue, ViewData) And now when you want to render this editor template for some string property on your view model: I use this class for inputs with type= (text , file) and select (drop down).
You can't set class for the the EditorFor. You could have many different tags inside this template. So you need to assign the class inside the editor template:
<div>
@Html.TextBoxForModel(x => x.StartDate, new { @class = "input datepicker" })
</div>
Or you could just use the TextBoxFor:
@Html.TextBoxFor(x => x.StartDate, new { @class = "input datepicker" }})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With