0
@Html.EditorFor(model => model.Id, new { @class = "form-control" } )

compiles to

<input class="text-box single-line" 
    data-val="true" data-val-email="The Id field is not a valid e-mail address." 
    data-val-required="The Id field is required." 
    id="Id" name="Id" value="" type="email">

How do I get Razor to apply the class form-control?

donquixote
  • 411
  • 2
  • 16
  • You might want to take a look at this: [Detailed answer][1] [1]: http://stackoverflow.com/a/27995734/3073551 – MarkovskI Jul 15 '15 at 20:23
  • 1
    @AleksandarMarkovski for future reference, you can link posts in comments like so: `[link](http://www.example/com)` [link](http://www.example.com) –  Jul 15 '15 at 20:37

3 Answers3

5

You should use the @Html.TextBoxFor html helper.

Using the @Html.EditorFor you can't do this.

The reason this is happening is the fact that the EditorFor html helper has first to find out what's the appropriate html element that should be generated for the property of your model. So it can't assign a css class to a not known element. On the other hand the TextBoxFor generates an input element with type text. Hence it can apply the css class you have picked from the start.

For instance, if we had this:

@Html.EditorFor(model => model.IsAdult)

the generated element would be a input element of type checkbox (I suppose that IsAdult is a boolean type).

gunr2171
  • 16,104
  • 25
  • 61
  • 88
Christos
  • 53,228
  • 8
  • 76
  • 108
3

Starting with MVC 5.1 you can do this as follows.

@Html.EditorFor(model => model.Id, new { htmlAttributes = new { @class = "form-control" } })

See What's new in ASP.NET MVC 5.1

sakura-bloom
  • 4,524
  • 7
  • 46
  • 61
3

Html.EditorFor has a few different overloads. The one you are using has this signature:

public static MvcHtmlString EditorFor<TModel, TValue>(
    this HtmlHelper<TModel> html,
    Expression<Func<TModel, TValue>> expression,
    object additionalViewData
)

That additionalViewData is not for html properties, it's passed into the routing engine.

It turns out that none of the overloads let you specify html properties. The reason is because EditorFor needs to decide what type of editor control to write to the page. It might be a textbox, or a drop down list, or a checkbox. Each control is different, and as such it wouldn't make sense to allow html property assignment when you don't know what html element(s) will be used.

The best thing to do instead is use something more specific for what you need, like TextBoxFor.

@Html.TextBoxFor(model => model.Id, 
    new { @class = "form-control" })

This method will let you pass in html properties and will assign them correctly.

gunr2171
  • 16,104
  • 25
  • 61
  • 88