How can I change this DropDownList declaration so that the disabled attribute is enable/disabled conditionally?
<%= Html.DropDownList("Quantity", new SelectList(...), new{@disabled="disabled"} %>
non-working example:
<%= Html.DropDownList("Quantity", new SelectList(...), new{@disabled=Model.CanEdit?"false":"disabled"} %>
p.s. adding an if condition around the entire statement is not a desired approach 🙂
EDIT: based on this extension method from another question I came up with the following extension:
public static IDictionary<string, object> Disabled (this object obj, bool disabled)
{
return disabled ? obj.AddProperty ("disabled", "disabled") : obj.ToDictionary ();
}
which can then be used as
<%= Html.DropDownList("Quantity", new SelectList(...), new{id="quantity"}.Disabled(Model.CanEdit) %>
Please don’t write spaghetti code. Html helpers are there for this purpose:
And then:
Or maybe you could come up with something even better (if the model contains the options):
You will also get the bonus of having more unit testable code.