Quote:
Originally Posted by jpatrick
I do not understand the current logic in the EditUser method of the UserController. When I update the user, all of the roles get checked regardless if it is selected or not. Here is the code ( VB.Net):
Code:
<Authorize(Roles:="Admin")> _
<AcceptVerbs("POST")> _
PublicFunction EditUser(ByVal id AsString, ByVal approved AsBoolean) As ActionResult'Is a list of all the user roles Dim removeRoleList As ArrayList = New ArrayList(Roles.GetAllRoles()) 'We are requesting the form variables directly from the form ForEach key AsStringIn Request.Form.KeysIf key.StartsWith("role.") ThenDim roleName AsString = key.Substring(5, key.Length - 5) removeRoleList.Remove(roleName) IfNot Roles.IsUserInRole(id, roleName) ThenRoles.AddUserToRole(id, roleName) EndIf EndIf
Next
ForEach removeRole AsStringIn removeRoleListRoles.RemoveUserFromRole(id, removeRole) Next Dim membershipUser As MembershipUser = Membership.GetUser(id) membershipUser.IsApproved = approved Membership.UpdateUser(membershipUser) TempData("SuccessMessage") = "User Information has been updated" ViewData("roles") = DirectCast(Roles.GetAllRoles(), String()) ViewData("PageTitle") = "Edit " & id Return View(membershipUser) EndFunction
Thanks,
|
The code adds the user to all the roles in your site (?), however it dosn't remove the user form the roles you have unchecked in your form. Here is my C# code. And yes, I had to reverse the logic. My brain works the other way around.
Code:
//Is a empty list of all the roles the user should have
ArrayList addRoleList = new ArrayList();
//We are requesting the form variables directly from the form
foreach (string key in Request.Form.Keys)
{
if (key.StartsWith("role."))
{
String userRole = key.Substring(5, key.Length - 5);
//System.Web.UI.WebControls.CheckBox test = Request.Form[key];
if (Roles.IsUserInRole(id, userRole))
{
Roles.RemoveUserFromRole(id, userRole);
}
//Checks the checkboxes
if (Request.Form[key].Contains("true"))
{
addRoleList.Add(userRole);
}
}
}
foreach (string addRole in addRoleList)
Roles.AddUserToRole(id, addRole)