Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
766 views
in Technique[技术] by (71.8m points)

asp.net mvc - Conditionally disable Html.DropDownList

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) %>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...