Conditional Attributes - Asp.Net MVC View
I have a requirement to add conditional disabled and class attributes to a dropdown form element. I have the following, however, it does not write any of the attributes in any state. Is there any way to get around this.
<%= Html.DropDownList("--Choose Make--", "models", ViewData["model_disabled"] == "false" ? new { @disabled = "disabled", @class = "test" } : null)%>
+1
source to share
1 answer
The problem is this:
ViewData["model_disabled"] == "false"
Returning from ViewData [] is an object. Calling == on two objects compares their id (i.e. are they the same instance of an object), not their equality (i.e., are they strings of the same value).
You can try instead:
((string)ViewData["model_disabled"]) == "false"
Edit:
With MvcContrib available extended syntax to cleaner syntax:
ViewData.Get<string>("model_disabled") == "false"
While this is a little cleaner, you will also notice it for a little longer. :-P
+2
source to share