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

1 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

2 Comments

Cheers Brad, is this the best way? Not sure I really like the readability of it at all.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.