Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP .NET MVC: How can I change the role of an user?

Tags:

c#

asp.net-mvc

In my app I have an Administrator role, and these kind of users can change the role of a user(client, manager...). I am using the built in Membership provider. Here is what I tried to do...

        [AcceptVerbs(HttpVerbs.Post)]
    public ActionResult EditRole(string usernameID, FormCollection formValues)
    {

        var db = new AppDataContext();
        var user = db.Users.SingleOrDefault(d => d.UserName == usernameID);
        string choosenRole = Request.Form["Roles"];                               

        var tuple = db.UsersInRoles.SingleOrDefault(d => d.UserId == user.UserId);
        var roleNameID = db.Roles.SingleOrDefault(d => d.RoleName == choosenRole).RoleId;
        tuple.RoleId = roleNameID;

        db.SubmitChanges();

        return RedirectToAction("Index");
    }

But, I got this error..

Value of member 'RoleId' of an object of type 'UsersInRole' changed. A member defining the identity of the object cannot be changed. Consider adding a new object with new identity and deleting the existing one instead.

I'm stucked. Any ideas?

like image 847
wallyqs Avatar asked May 06 '09 18:05

wallyqs


1 Answers

Rather than trying to access the membership tables directly from the db (datacontext) you should be using the User, Roles, and Membership static classes provided within your action code there.

Like this:

System.Web.Security.Roles.AddUserToRole(usernameID, choosenRole);

Assuming that your usernameID is the string key of the user you want to change and choosenRole contains the role name key you want to add the user to:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult EditRole(string usernameID, FormCollection formValues)
{
    string choosenRole = Request.Form["Roles"];                               
    System.Web.Security.Roles.AddUserToRole(usernameID, choosenRole);

    return RedirectToAction("Index");
}
like image 174
Matt Kocaj Avatar answered Oct 13 '22 00:10

Matt Kocaj