基于用户角色的批量禁用复选框-MVC Razor

时间:2018-10-02 13:35:30

标签: c# asp.net-mvc razor html-helper

我在MVC应用程序中定义了用户角色。本质上,我想要的是这样:

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

我知道我可以做类似的事情,但是页面上大约有100个复选框,重复添加了disable属性的所有代码行似乎令人讨厌。有没有更好的办法?我也不反对使用某些jQuery完成此操作:

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>
}

2 个答案:

答案 0 :(得分:4)

您可以检查模型并将object设置为已禁用作为html helper的属性。

object attributes = null;

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

然后像这样将其用于您的助手

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

当角色出现问题时,它将禁用复选框,否则它将保持启用状态。

答案 1 :(得分:1)

尝试一下

<script type="text/javascript">
    function Uncheckall() {

        $('table input[type=checkbox]').attr('disabled', 'true');
    }
</script>