Search code examples
c#asp.net-mvcmvc-editor-templatesreadonly-attribute

MVC EditorFor Optionally ReadOnly


Yesterday, after extensive testing, I got the following to optionally apply the readonly attribute to a control based on the value of ViewBag.CanEdit;

@Html.EditorFor(m => m.Location, new { htmlAttributes = new { @class = "form-control", @readonly = (ViewBag.CanEdit == true ? Html.Raw("") : Html.Raw("readonly")) } })

Based on the success of this testing I implemented and tested it in several parts of my project. Today I started on a new section of the code and commenced implementing the same code only to have it consistently fail - every control is readonly.

When I inspected the controls they either have readonly or readonly=readonly as the attribute? I then went back to the code I refactored yesterday to find the same problem; every control is now readonly regardless of the value of ViewBag.CanEdit?

Can anyone explain why this would have worked yesterday but fails today?


Solution

  • Try this

    @Html.TextBoxFor(model => model.Location, !ViewBag.CanEdit 
        ? (object)new { @class = "form-control", @readonly ="readonly" } 
        : (object)new { @class = "form-control" })