I want the disabled attribute be added to a textbox based on a condition
@Html.TextBoxFor(m => m.kidsNumber, new { (Model.kidsDropDown != "2") ? "@disabled" : ""})
I want the disabled attribute be added to a textbox based on a condition
@Html.TextBoxFor(m => m.kidsNumber, new { (Model.kidsDropDown != "2") ? "@disabled" : ""})
Use
@Html.TextBoxFor(m => m.kidsNumber, Model.kidsDropDown != "2" ? new {disabled = "disabled"} : null )
Note also if you need to add multiple attributes, then it needs to be in the format (where the attributes are cast to object
@Html.TextBoxFor(m => m.kidsNumber, Model.kidsDropDown != "2" ? (object)new { @disabled = "disabled", @class="form-control" } : (object)new { @class="form-control" })
If you have multiple textboxes that use the same sets of attributes, you can assign these to variables in the view
@{
object number = new { @type = "number", @class="form-control" };
object disabledNumber = new { @disabled = "disabled", @class="form-control" };
}
and in the form
@Html.TextBoxFor(m => m.kidsNumber, Model.kidsDropDown != "2" ? disabledNumber : number)
@Html.TextBoxFor(m => m.anotherProperty, AnotherCondition ? disabledNumber : number)
.....
You have not said which attribute you want to set ::
you code is without attribute and you should use use readonly instead because disabled fields are not posted on form submit
@Html.TextBoxFor(m => m.kidsNumber, new { (Model.kidsDropDown != "2") ? "@disabled" : ""})
For Disabled attribute Use::
@Html.TextBoxFor(m => m.kidsNumber, Model.kidsDropDown != "2" ? new {disabled = "disabled"} : null )
For readonly Use something like::
@Html.TextBoxFor(m => m.kidsNumber, new { @readonly= (Model.kidsDropDown != "2" ? "readonly" : "")})