c# - 如何绑定(bind)CheckBoxFor

标签 c# asp.net-mvc

我有一组“权限”。每个权限都具有三个属性:Id、Name 和 HasPermission。例如,考虑以下对象:

public class AccessPerm
{
  int PermId {get;set;}
  string PermName {get;set}
  bool HasPerm {get;set;}
}

public class UserProfile
{
  Collection<AccessPerm> UserPerms {get;set;}
}

所以我想使用 CheckBoxFor 帮助器来创建复选框,以便可以设置用户的权限。如果您选中该框,则 HasPerm 应该为 true。如果取消选中它,HasPerm 应该为 false。我遇到的问题是我没有找到将 PermId 和 HasPerm 属性绑定(bind)到复选框的方法。我使用以下代码绑定(bind) HasPerm 属性,但它没有用,因为我不知道 PermId。

<%
  for(int ix=0; ix< Model.UserProfile.Perms.Count; ix++)
  {
    Html.CheckBoxFor(model => model.UserProfile.Perms[ix].HasPerm);
  }
%>

这段代码确实绑定(bind)了HasPerm,并且值是正确的。但是,由于我没有 id,因此我无法对该值执行任何操作。请指教。

最佳答案

您可以将其包含为隐藏字段:

<% for(int ix = 0; ix < Model.UserProfile.Perms.Count; ix++) { %>
    <%= Html.HiddenFor(model => model.UserProfile.Perms[ix].PermId) %>
    <%= Html.CheckBoxFor(model => model.UserProfile.Perms[ix].HasPerm) %>
<% } %>

这样,您将在 POST Controller 操作中获得相同的列表,其中包含 id 以及是否已选择它。

关于c# - 如何绑定(bind)CheckBoxFor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7557897/

相关文章:

c# - RadioButtonList:OnSelectedIndexChanged 未触发

c# - PayPal Error while Make Payment Using card 10752 错误消息

c# - ASP.NET MVC - 当模型添加附加字段时更新强类型 View 的简单方法?

javascript - Kentor SAML2 授权问题

c# - 林克 : Select multiple values and assign to select with specific option/value

c# - 需要时髦的 LINQ(第 2 部分)

c# - 使方法异步运行的最佳方法是什么?

c# - 我怎样才能最好地利用 Json.NET 修改现有 JSON 对象的部分内容?

c# - 最快的 Sobel 边缘检测 C#

c# - 编辑 ID - 存储更新、插入或删除语句影响了意外的行数 (0)