tags:

views:

387

answers:

2

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 :)

+1  A: 

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"}) %>
bobince
+5  A: 

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

public static string 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.

Darin Dimitrov
How does using a helper make unit testing your views easier?
Todd Smith
You cannot unit test views due to the nature of the WebForms engine. You could though test extension methods. This way your view will no longer contain conditional logic worth unit testing. By testing the extension method you make sure that all views using it will behave as you expect and have the exact markup depending on the `CanEdit` property on your model.
Darin Dimitrov