How to conditionally disable <select> from tag helper?

Viewed 7968

My goal is to conditionally disable a drop-down depending on the status of the model object passed to the view.

The following code correctly renders a disabled <select> tag (but not conditionally):

<select class="form-control" asp-for="Priority" asp-items="@priorityList" disabled></select>

The following does not. The attribute disabled does not appear in the page source for the rendered page:

@{ string disabled = Model.CaseMode == Mode.Active ? "" : "disabled"; }
<select class="form-control" asp-for="Priority" asp-items="@priorityList" @disabled></select>

Also, the following also does not disable the <select> tag.

<select class="form-control" asp-for="Priority" asp-items="@priorityList" @((Model.CaseMode == Mode.Closed) ? "disabled" : "")></select>

I assume the issue has to do with the tag helper processing the <select> tag before the string substitution is done in the template. Can anyone suggest how I can conditionally disable this element without have to render two separate elements in an if else structure?

3 Answers

Since disabled="false" didn't work for me and didn't want to add an extension class for just one select list... here's how I solved it:

@{ string disabled = Model.CaseMode == Mode.Active ? "disabled" : null; }
<select  asp-for="Priority" class="form-control" disabled="@disabled" asp-items="@priorityList"></select>

Another posible solution would be to have your condition in a ViewData dictionary and evaluate once document has been loaded:

@if((bool)ViewData["YourModelCondition"]){
     $('#selectListID').prop('disabled', 'disabled');
}

Note: You will need to specify an ID for the select if you use the second solution.

Related