views:

738

answers:

2

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.

A: 

Be sure to check this topic on SO.

bastijn
+3  A: 

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.

mattruma
Simple and to the point - thanks.
Pino