MVC3 Conditionally disable Html.TextBoxFor()

MikeTWebb picture MikeTWebb · Jan 31, 2012 · Viewed 52.7k times · Source

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 logged into the system. I tried using

 @Html.TextBoxFor(model => model.ProposalName, new { @ViewBag.IsDisabled })

Where @ViewBag.IsDisabled is set to either String.Empty or "disabled" in the Controller. However, this renders as IsDisabled='disabled' or IsDisabled="" so the control is not disabled. When I tried

@Html.TextBoxFor(model => model.ProposalName, new { @ViewBag.Disabled })

The control was always disabled even if ViewBag.Disabled contained no text. How can I conditionally disable the Html.TextBoxFor() controls?

Answer

epignosisx picture epignosisx · Jan 31, 2012

Try

@Html.TextBoxFor(model => model.ProposalName, ViewBag.Disabled ? (object)new { disabled="disabled" } : new {})