Conditionally disable Html.DropDownList

Viewed 37385

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) %>
8 Answers

Please don't write spaghetti code. Html helpers are there for this purpose:

public static MvcHtmlString DropDownList(this HtmlHelper html, string name, SelectList values, bool canEdit)
{
    if (canEdit)
    {
        return html.DropDownList(name, values);
    }
    return html.DropDownList(name, values, new { disabled = "disabled" });
}

And then:

<%= Html.DropDownList("Quantity", new SelectList(...), Model.CanEdit) %>

Or maybe you could come up with something even better (if the model contains the options):

<%= Html.DropDownList("Quantity", Model) %>

You will also get the bonus of having more unit testable code.

You can do:

var dropDownEditDisable = new { disabled = "disabled" };
var dropDownEditEnable = new { };

object enableOrDisable = Model.CanEdit ? 
           (object)dropDownEditEnable : (object)dropDownEditDisable;

@Html.DropDownList("Quantity", new SelectList(...), enableOrDisable)

Html.DropDownListFor() can be long, so doing that, there is no need to repeat it.

I don't know if ASP.NET offers a more succinct special-case approach, but presumably you could do:

<%= Html.DropDownList("Quantity", new SelectList(...), Model.CanEdit? new{@class="quantity"} : new{@class="quantity", @disabled:"disabled"}) %>
Related