Click here to Skip to main content
15,891,431 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have 2 roles Admin and Donor

Upon registration any user must be added to the Donor role. How do I achieve this with identity and mvc5.

C#
[HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = model.GetUser();
                var result = await UserManager.CreateAsync(user, model.Password);
                UserManager.AddToRole(user.UserName, "User");
                if (result.Succeeded)
                {
                    return RedirectToAction("Index", "Account");
                }

            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }



I getthe following error System.InvalidOperationException: UserId not found.
Posted
Updated 18-Aug-14 4:11am
v2
Comments
Snesh Prajapati 18-Aug-14 10:21am    
Let me know if my answer works for you. Thanks.
ZainNabi 18-Aug-14 12:28pm    
Thank you. It does assign the role to the user. What I need to do now is navigate to a specific view with a layout for that role. Any ideas
Snesh Prajapati 18-Aug-14 13:31pm    
Most Welcome !! use multiple layout pages and write logic in _ViewStart file, for more..http://stackoverflow.com/questions/8419826/dynamic-change-viewstart-layout-path-in-mvc-3
ZainNabi 18-Aug-14 13:36pm    
Maybe you can help me with my other question??

I have a drop down with certain values

<pre lang="cs">@using (Html.BeginForm())
{

@Html.DropDownList("Animal Type",
new SelectList((System.Collections.IEnumerable) ViewData["Animal"], "animal_type"))

}</pre>

my controller action for that method is

<pre lang="sql">[HttpGet]
public ActionResult create()
{
var animal = from x in db.Animals
select x.animal_type;
ViewData["Animal"] = animal;
return View();
}</pre>


After selecting a value from the drop down it should display the specific partial view on the same view

1 solution

First check for result, then only add role. That mean change the position of UserManager.AddToRole like:

C#
var user = model.GetUser();
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
    result = UserManager.AddToRole(user.Id, "User");

You can add multiple roles too if you have a list of roles.
C#
foreach(var role in roles)
{
   var isInRole = await UserManager.IsInRoleAsync(userid, role)
   if(!isInRole)
   {
      await UserManager.AddToRoleAsync(userid, role);
   }
}
 
Share this answer
 
Comments
Zayne Frauendorf 10-Apr-17 14:16pm    
Thank you very much, this was very helpful.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900