Search code examples
c#asp.net-mvcrazorhtml-helper

Bulk disable checkboxes based on User Role - MVC Razor


I have user roles defined in my MVC application. Essentially, what I want is this:

if (User.IsInRole = ("staff"))
   {
      // disable all checkboxes
   }

I know I could do something like this, but there's about 100 checkboxes on the page and it seems obnoxious to repeat all the lines of code with the disabled attribute added. Is there a better way? I am not opposed to using some jQuery to accomplish this either:

if (User.IsInRole = ("staff"))
{
   <tr>
     <td>Centroid</td>
     <td><input type="checkbox" name="Staff" checked disabled /></td>
     <td>@Html.CheckBoxFor(m => m.NBTC_FA_Centroid, new {@disabled = "disabled")</td>
     <td>@Html.CheckBoxFor(m => m.Contract_FA_Centroid, new {@disabled = "disabled")</td>
     <td>@Html.CheckBoxFor(m => m.Coord_FA_Centroid, new {@disabled = "disabled")</td>
     <td>@Html.CheckBoxFor(m => m.NGO_FA_Centroid, new {@disabled = "disabled")</td>
     <td>@Html.CheckBoxFor(m => m.Public_FA_Centroid, new {@disabled = "disabled")</td>
   </tr>
}
else
{
   <tr>
        <td>Centroid</td>
        <td><input type="checkbox" name="Staff" checked disabled /></td>
        <td>@Html.CheckBoxFor(m => m.NBTC_FA_Centroid)</td>
        <td>@Html.CheckBoxFor(m => m.Contract_FA_Centroid)</td>
        <td>@Html.CheckBoxFor(m => m.Coord_FA_Centroid)</td>
        <td>@Html.CheckBoxFor(m => m.NGO_FA_Centroid)</td>
        <td>@Html.CheckBoxFor(m => m.Public_FA_Centroid)</td>
   </tr>
}

Solution

  • You can check your model and set object as disabled as attribute of html helper.

    object attributes = null;
    
    if (User.IsInRole = ("staff"))
    {
        attributes = new { disabled = "disabled" };
    }
    

    and then use it to your helper like this

     @Html.CheckBoxFor(model => model.Status, attributes)
    

    It will disable checkboxes when role is stuff otherwise it will remain enable.