ASP.Net MVC - 处理多个复选框 [英] ASP.Net MVC - Handle Multiple Checkboxes
问题描述
好的,我有一个基于角色的权限系统,并希望管理员能够编辑每个角色的权限。为了做到这一点,我需要加载大量的复选框,但我很难从获取的返回数据
Ok, I have a role based permission system in place and would like admin's to be able to edit the permissions for each role. To do this I need to load lots of checkboxes, however I'm struggling with getting the return data from the View
请注意:我已经找到了,我找到了类似的问题,但仍然找不到解决方案。
Please Note: I have looked around, I have found similar questions but as of yet cannot find a solution.
<%
Html.BeginForm();
string lastGroup = "";
foreach (var CurPermission in Model)
{
%>
<%=Html.CheckBox("Permissions", CurPermission.Checked, new { ID = CurPermission.PermissionId}) + " " + CurPermission.PermissionValue%>
<br />
<%
}
%>
<input type="submit" value="Submit" />
<%
Html.EndForm();
%>
和控制器,
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditPermissions(String[] Permissions)
{
foreach (var CurPermission in Permissions)
{
Debug.WriteLine(CurPermission);
}
return View();
}
显然,我需要知道哪些框没有被选中,是。但是在返回值中,由于整体(真,假),我无法确定哪个值与哪个复选框相关。
Obviously I need to know which boxes are not checked as well as the ones that are. But in the return values because of the whole ("true,false") I cant work out which value relates to which checkbox.
有关修复的任何建议或者
Any suggestions as to a fix or prehaps an alternate method would be appriciated.
推荐答案
这里有一些代码片段,我们用来将成员分配给项目,希望这个帮助你!
Here are some snippets of code that we use to assign members to a project, hopefully this helps you out!
在视图中,我们有:
<p>
<label>
Select project members:</label>
<ul>
<% foreach (var user in this.Model.Users)
{ %>
<li>
<%= this.Html.CheckBox("Member" + user.UserId, this.Model.Project.IsUserInMembers(user.UserId)) %><label
for="Member<%= user.UserId %>" class="inline"><%= user.Name%></label></li>
<% } %></ul>
</p>
在控制器中,我们有:
// update project members
foreach (var key in collection.Keys)
{
if (key.ToString().StartsWith("Member"))
{
int userId = int.Parse(key.ToString().Replace("Member", ""));
if (collection[key.ToString()].Contains("true"))
this.ProjectRepository.AddMemberToProject(id, userId);
else
this.ProjectRepository.DeleteMemberFromProject(id, userId);
}
}
使用Html复选框时要记住的主要事情助手是使用contains()来确定true或false。
The main thing to remember when working with the Html Checkbox Helper is to use contains() to determine true or false.
这篇关于ASP.Net MVC - 处理多个复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!