asp.net-mvc-3conditional-statementshtml.textbox

MVC3 Conditionally disable Html.TextBoxFor()


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?


Solution

  • Try

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