如何从viewbag中的字符串列表生成复选框?

时间:2016-10-03 14:00:01

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

我的控制器方法中有以下代码返回视图:

public ActionResult Create()
{
  var allprivs = new SQLRolerecord().GetAllPrivsInApp();
  ViewBag.AllPrivsInApp = allprivs;
  return View();
}

GetAllPrivsInApp方法返回IEnumerable<string>。然后在视图中,我尝试从返回的字符串列表中创建一个复选框列表,我有以下Razor / html:

<table>
@{
  List<string> privsInApp = ViewBag.AllPrivsInApp;
  foreach (var priv in privsInApp)
  {
    @Html.CheckBox(priv,  new { value = priv, @label=priv})
  }
}
</table>

这会生成我期望的正确数量的复选框,但是,我不会在它们旁边看到标签。在应用程序运行时查看HTML源代码时,我可以看到每个复选框的name和其他几个属性包含我期望的每个文本框的文本值。如何让文本显示在每个复选框旁边?

以下是显示内容的屏幕截图:

enter image description here

以下是生成的来源:

<table>
<input id="AdminRead" label="AdminRead" name="AdminRead" type="checkbox" value="AdminRead" /><input name="AdminRead" type="hidden" value="false" /><input id="AdminWrite" label="AdminWrite" name="AdminWrite" type="checkbox" value="AdminWrite" /><input name="AdminWrite" type="hidden" value="false" /><input id="Privilege1" label="Privilege1" name="Privilege1" type="checkbox" value="Privilege1" /><input name="Privilege1" type="hidden" value="false" /><input id="Privilege2" label="Privilege2" name="Privilege2" type="checkbox" value="Privilege2" /><input name="Privilege2" type="hidden" value="false" /><input id="Privilege3" label="Privilege3" name="Privilege3" type="checkbox" value="Privilege3" /><input name="Privilege3" type="hidden" value="false" /><input id="Privilege4" label="Privilege4" name="Privilege4" type="checkbox" value="Privilege4" /><input name="Privilege4" type="hidden" value="false" /><input id="Privilege5" label="Privilege5" name="Privilege5" type="checkbox" value="Privilege5" /><input name="Privilege5" type="hidden" value="false" /><input id="Privilege6" label="Privilege6" name="Privilege6" type="checkbox" value="Privilege6" /><input name="Privilege6" type="hidden" value="false" /><input id="Privilege7" label="Privilege7" name="Privilege7" type="checkbox" value="Privilege7" /><input name="Privilege7" type="hidden" value="false" /><input id="Privilege8" label="Privilege8" name="Privilege8" type="checkbox" value="Privilege8" /><input name="Privilege8" type="hidden" value="false" /><input id="Privilege9" label="Privilege9" name="Privilege9" type="checkbox" value="Privilege9" /><input name="Privilege9" type="hidden" value="false" /><input id="Privilege0" label="Privilege0" name="Privilege0" type="checkbox" value="Privilege0" /><input name="Privilege0" type="hidden" value="false" />
</table>

谢谢。

1 个答案:

答案 0 :(得分:1)

如果您只是为复选框寻找标签,那么这应该有效:

<table>
@{
  List<string> privsInApp = ViewBag.AllPrivsInApp;
  foreach (var priv in privsInApp)
  {
        <tr>
            <td>@Html.Label(priv)</td>
            <td>@Html.CheckBox(priv, new { value = priv })</td>
        </tr>
  }
}
</table>

这也假设您正在使用Bootstrap进行样式化。

如果有帮助,请告诉我!