如何绑定CheckBoxFor [英] How to bind CheckBoxFor

查看:193
本文介绍了如何绑定CheckBoxFor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有权限的集合。每个权限将有三个属性:ID,名称和HasPermission。因此,作为一个例子,考虑以下对象:

I have a collection of "permissions". Each permission would have three properties: Id, Name, and HasPermission. So as an example, consider the following object:

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应该是真实的。如果取消选中它,HasPerm应该是假的。我遇到的问题是我没有看到绑定两个PermId和HasPerm属性复选框的一种方式。我用下面的code到HasPerm属性绑定,而是因为我不知道它PermId是没有用的。

So I want to use the CheckBoxFor helper to create checkboxes so that one can set the user's permissions. If you check the box, then HasPerm should be true. If you uncheck it, HasPerm should be false. The problem I am having is I don't see a way to bind both the PermId and the HasPerm properties to the checkbox. I used the following code to bind the HasPerm property, but it is not useful because I don't know the PermId.

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

这code确实结合HasPerm和值是正确的。然而,由于我没有身份证,我不能做的任何有价值的东西。请指教。

This code does indeed bind HasPerm, and the value is correct. However, since I don't have the id, I can't do anything with the value. Please advise.

推荐答案

您可以把它作为隐藏字段:

You could include it as hidden field:

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

此方式,您将得到相同的列表中包含该ID的POST控制器动作,它是否被选中。

This way you will get the same list in your POST controller action containing the id and whether it is selected.

这篇关于如何绑定CheckBoxFor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆