Why can't I pass in html attributes to EditorFor()
? eg;
<%= Html.EditorFor(model => model.Control.PeriodType,
new { disabled = "disabled", readonly = "readonly" }) %>
I don't want to use metadata
Update: The solution was to call this from the view :
<%=Html.EditorFor( model => model.Control.PeriodEndDate, new {Modifiable=model.Control.PeriodEndDateModifiable})%>
and use ViewData["Modifiable"]
in my custom EditorTemplates/String.ascx where I have some view logic that determines whether to add readonly and/or disabled attributes to the input
The anonymous object passed into EditorFor()
is a parameter called additionalViewData
and its properties are passed to the editor template in the ViewData
collection.
Update MVC 5.1 now supports the below approach directly, so it works for built in editor too. http://www.asp.net/mvc/overview/releases/mvc51-release-notes#new-features (It's either a case of Great mind thinking alike or they read my answer :)
End Update
If your using your own editor template or with MVC 5.1 which now supports the below approach directly for built in editors.
@Html.EditorFor(modelItem => item.YourProperty,
new { htmlAttributes = new { @class="verificationStatusSelect", style = "Width:50px" } })
then in your template (not required for simple types in MVC 5.1)
@Html.TextBoxFor(m => m, ViewData["htmlAttributes"])