How do I disable my @Html.ListBoxFor()

2k Views Asked by At

I need to be able to disable this ListBoxFor() depending on the Review status. Although the code below works it shows all list items.

@Html.ListBoxFor(m => m.ListOptions, filetypes, Model.IsUnderReview ? new { @class = "disabled" } : new { @class = "multiselectFileTypes" })

What would be the syntax to disable it but just so it shows '2 items selected'?

2

There are 2 best solutions below

0
On BEST ANSWER

It seems the answer is to use the Html.helper command HiddenFor(), like this

@if (Model.IsUnderReview)
{
    //You then need to generate a hidden input for each value in SelectedRoles, as it's an array
    @Html.HiddenFor(m => m.SelectedRoles) 
}
else
{
    @Html.ListBoxFor(x => x.SelectedRoles, filetypes, new { @class = "multiselectFileTypes" , id = "staticFieldM_" + Model.ID})
}

By creating a hidden input for each SelectedRole item you then disable the whole list.

3
On

You cannot do inline condition checking for the htmlAttributes parameter.

This should work.

@using (Html.BeginForm())
{
  <label>Select something </label>
  if (!Model.IsUnderReview )
  {
    @Html.ListBoxFor(m => m.ListOptions, filetypes, new { @class = "multiselectFileTypes"})
  }
  else
  {
    @Html.ListBoxFor(m => m.ListOptions, filetypes, new { disabled = "disabled" })
  }
}