I have a C# .Net web app. In that app I need to conditionally disable Html.TextBoxFor controls (also Html.DropDownListFor controls) based on who is
Here is the method I use, which doesn't require extensions, and doesn't limit you to only one HTML attribute. It assumes there is a boolean property named "Disabled" in your model, but you could put whatever you wanted in there, as long as it evaluates to boolean for the ternary operator:
@Html.TextBoxFor(model => model.Whatever,
new Dictionary() {
{ "size", "5" },
{ "class", "someclasshere" },
{ model.Disabled ? "disabled" : "data-notdisabled", "disabled" }
})
The limitation with the standard shortcut notation is that the name of the attribute cannot be dynamic. By creating a dictionary of the correct type, you can then make the attribute name dynamic, and you then pass that dictionary to the textbox as the dictionary of attributes. When the field is not to be disabled, it passes an attribute named "data-notdisabled" instead of one named "disabled", which the browser will then ignore.