I have a requirement to add conditional disabled & class attributes to a dropdown form element. I have the following however it does not write out either of the attributes in any state. Is there a way around this.
<%= Html.DropDownList('--Choose Make--', 'models', ViewData['model_disabled'] == 'false' ? new { @disabled = 'disabled', @class = 'test' } : null)%>
The problem is:
The return from ViewData[] is object. Calling == with two objects compares their identity (i.e., are they the exact same object instance), not their equality (i.e., are the strings the same value).
You can try this instead:
Edit:
A slightly cleaner syntax is available with the MvcContrib ViewData extensions:
Although this feels a little cleaner, you’ll also notice it’s slightly longer. :-p