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) %>
There is no need to add helper methods, you can just use
<%= Html.DropDownList("Quantity", new SelectList(...), IsEditable == true ? new { @disabled = "disabled" } as object : new {} as object %>
If you were to remove the as object
entries this wouldn't work because by default new {}
is a dynamic object compiled at runtime, therefore the two possible objects must have the same properties. But the Html attributes parameter is actually just an object, so these dynamics can be cast as objects to get around this.
This solution even allows you to use multiple HTML attributes where one is optional and another is not, i.e class='whatever'
is not optional but disabled
is so you put class='whatever'
in both the objects, but the optional one only in the first. Dimitrov's answer does not support any custom attributes other than disabled.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With