views:

107

answers:

2

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["PeriodEndDateModifiable"] 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

+1  A: 

EditorFor works with metadata, so if you want to add html attributes you could always do it. Another option is to simply write a custom template and use TextBoxFor:

<%= Html.TextBoxFor(model => model.Control.PeriodType, 
    new { disabled = "disabled", @readonly = "readonly" }) %>    
Darin Dimitrov
The metadata won't work because the html attributes vary depending on other properties in the model, in other words domain or viemodel logic should determine the html attributes not static metadata. Or am I missing the point, can I set metadata dynamically?
Gaz Newt
What is `PeriodType`? Isn't it a simple property? If it is a complex object you could could customize the whole template by placing a partial in `~/Views/ControllerName/EditorTemplates/SomeType.ascx` where `SomeType` is the type name of the `PeriodType` property.
Darin Dimitrov
Also your suggested code would mean passing the whole model into a partial template which accesses a specific property, this would mean I have a partial for each property?
Gaz Newt
PeriodType is a simple object, but it may not be editable at the front end depending on domain permissions and workflow
Gaz Newt
I get you now. I can use <%=Html.EditorFor( model => model.Control.PeriodEndDate, new {Modifiable=model.Control.PeriodEndDateModifiable})%> and use ViewData["PeriodEndDateModifiable"] in my custom EditorTemplates/String.ascx. Thanks
Gaz Newt
+1  A: 

If you don't want to use Metadata you can use a [UIHint("PeriodType")] attribute to decorate the property or if its a complex type you don't have to decorate anything. EditorFor will then look for a PeriodType.aspx or ascx file in the EditorTemplates folder and use that instead.

jfar
Thanks, I may end up doing that if the if/else in my editor template is only required for certain fields
Gaz Newt