tags:

views:

442

answers:

1

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)%>
+2  A: 

The problem is:

ViewData["model_disabled"] == "false"

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:

((string)ViewData["model_disabled"]) == "false"

Edit:

A slightly cleaner syntax is available with the MvcContrib ViewData extensions:

ViewData.Get<string>("model_disabled") == "false"

Although this feels a little cleaner, you'll also notice it's slightly longer. :-p

Brad Wilson
Cheers Brad, is this the best way? Not sure I really like the readability of it at all.
redsquare
I ran into something similar today, and discovered yet another syntax: *false.Equals(ViewData["model_disabled"])*. Although the syntax may seem a little odd at first, it also is concise and you get "automatic" null-checking without having to resort to things like encoding your boolean into strings or using frameworks. Cheers.
Daniel Liuzzi