I am working on an asp.net mvc-5 web application , and i wrote the following :-
@Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
&
@Html.EditorFor(model => model.Name, new { @class = "form-control" })
but this will not have any effect on the generated html, but if i changed the EditorFor
to be TextboxFor
i will get the effect for the form-control class ? can anyone advice on this please ? i read that this is supported only inside asp.net mvc 5.1 ? so what are the available approaches i can follow to get this working other than upgrading my asp.net mvc-5 to asp.net mvc 5.1 , to eliminate the risk of upgrading?
Can anyone adivce ?
Yes, to pass html attributes to a standard
EditorFor()
you need MVC-5.1+. If you want to replicate this with MVC-5, you can create a custom editor template and pass the attributes using the overload that acceptsadditionViewData
. For example, create a newEditorTemplate
named "String.cshtml" to apply the template for all properties that are typeofstring
/Views/Shared/EditorTemplates/String.cshtml
and in the view
or create a specific
EditorTemplate
/Views/Shared/EditorTemplates/MyCustomTemplate.cshtml
and in the view
The second example shows how to respect the
DisplayFormat
attribute as mentioned in your comments above, for examplewill format the value as a currency string.
This answer also gives some other options including creating a custom html helper for rendering bootstrap controls
This works: