Search code examples
asp.net-mvcrazorhtml.listboxfor

How do I disable my @Html.ListBoxFor()


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'?


Solution

  • 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.