ASP.NET MVC - Disable Html Helper control using boolean value from Model

asp.net, asp.net-mvc, html

Solution

This here should do the trick:

<%= Html.TextBox("MyTextbox", Model.MyValuenew,           
      (Model.IsMyTextboxEnabled() ? (object) new {id = "MyTextbox", @class = "MyClass"}
                                  : (object) new {id = "MyTextbox", @class = "MyClass", disabled="true" })) %>

Problem

I am outputting a textbox to the page using the Html helpers. I want to add the disabled attribute dynamically based on whether or not a boolean value in my model is true or false. My model has a method that returns a boolean value: ``` <% =Model.IsMyTextboxEnabled() %> ``` I currently render the textbox like follows, but I want to now enabled or disable it: ``` <% =Html.TextBox("MyTextbox", Model.MyValuenew { id = "MyTextbox", @class = "MyClass" })%> ``` If the return value of Model.IsMyTextboxEnabled() == true I want the following to be output: ``` <input class="MyClass" id="MyTextbox" name="MyTextbox" type="text" value="" /> ``` If it == false, I want it to output as: ``` <input class="MyClass" id="MyTextbox" name="MyTextbox" type="text" value="" disabled /> ``` What is the cleanest way to do this?

Original source

Related problems