Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Html.EditorFor ignoring my specified class

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?

like image 602
Alex Avatar asked Oct 23 '12 12:10

Alex


People also ask

How do I set an anonymous class in editorfor?

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.

What is the editorfor method in HTML?

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.

Can I Pass HTML attributes to custom editor editor templates?

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.

How to render an editor template for string in cshtml?

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).


1 Answers

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" }}) 
like image 187
Max Avatar answered Oct 11 '22 00:10

Max