BattlFrog
BattlFrog

Reputation: 3407

How do I set dynamic readonly on MVC 5 razor view?

I have a bool value IsAcre. If true, then textbox needs to be able to accept a value. If false, the textbox should be readonly. I am trying a couple different ways:

   @Html.EditorFor(model => model.Activity.Acres, new { htmlAttributes = new { @class = "form-control", Model.Activity.IsAcres ? null : @readonly = "readonly" }} ) 

and

  @Html.TextBoxFor(model => model.Activity.Volume, new { @class = "form-control", @readonly = "@Model.Activity.IsVolume" })

First one seems to be syntacticlly incorrect, the second one renders as:

readonly="False"

Even though it renders the false readonly, the textbox is still set to readonly, I assume because the bool value is passed as a string.

Is there a way to do this inline or will have to if/else on the entire textbox?

Upvotes: 0

Views: 5427

Answers (1)

user3559349
user3559349

Reputation:

The readonly attribute is a boolean attribute which means that its presence represents the true value, so your second code snippet that renders readonly="False" makes the input readonly (although its invalid html). Note also from the specs

The values "true" and "false" are not allowed on boolean attributes. To represent a false value, the attribute has to be omitted altogether.

You need to use the code in your first code snippet to ensure the attribute is either added or omitted, although you could use alternatives such as

@{ var attributes = Model.Activity.IsAcres ? (object)new { @class = "form-control"} : (object)new { @class = "form-control", readonly = "readonly" }; }
@Html.TextBoxFor(model => model.Activity.Volume, attributes)

and if this is something you use regularly, then you could create a HtmlHelper extension method that conditionally adds the attribute based on the value of another property (say)

@Html.ReadOnlyTextBoxIf(m => m.Activity.Acres, Model.Activity.IsAcres, new { @class = "form-control" })

Upvotes: 4

Related Questions