ASP.Net MVC - Handle Multiple Checkboxes

邮差的信 提交于 2019-11-30 15:57:56

问题


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();
%>

and the controller,

[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.


回答1:


Here are some snippets of code that we use to assign members to a project, hopefully this helps you out!

In the view we have:

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

In the controller we have:

// 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);
    }
}

The main thing to remember when working with the Html Checkbox Helper is to use contains() to determine true or false.




回答2:


Be sure to check this topic on SO.



来源:https://stackoverflow.com/questions/1795812/asp-net-mvc-handle-multiple-checkboxes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!