prezequias
prezequias

Reputation: 267

Asp Net MVC Role Security

I am stuck with roles in my asp net mvc 5 project.I can create role type on database but cannot retrive them into User registration, as it display an error on my Register.cshtml "There is no ViewData item of type '' that has the key 'Name". Can anyone please help me. thanks in advance. Here is my controller:

 private ApplicationSignInManager _signInManager;
            private ApplicationUserManager _userManager;
            ApplicationDbContext context;
            public AccountController()
            {       

            }

            public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager )
            {
                UserManager = userManager;
                SignInManager = signInManager;
                context = new ApplicationDbContext();
            }

My Register Action

 [AllowAnonymous]
        public ActionResult Register()
        {
            return View();
        }

        //
        // POST: /Account/Register
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
                ViewBag.Name = new SelectList(context.Roles.ToList(), "Name", "Name");
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    await this.UserManager.AddToRoleAsync(user.Id, model.Name);
                    await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
                    return RedirectToAction("Index", "Home");
                }
                AddErrors(result);
            }
            // If we got this far, something failed, redisplay form

            return View(model);
        }

My View

<div class="form-group">
            @Html.Label("Select Your User Type", new { @class = "col-md-2 control-label" })
            <div class="col-md-10">
                @Html.DropDownList("Name")

            </div>

Upvotes: 1

Views: 398

Answers (1)

rashfmnb
rashfmnb

Reputation: 10538

although i have posted another way to find the roles but your code us fine did you enter any roles in table

AspNetRoles

and created the relation between user and roles in table

AspNetUserRoles

To find all the role for specific user you can use the following code

    RoleBasedSecurity.Models.ApplicationDbContext context = new ApplicationDbContext();
    ApplicationUser au = context.Users.First(u => u.UserName == "[email protected]");

    foreach (IdentityUserRole role in au.Roles)
    {
        string name = role.RoleId;
        string RoleName = context.Roles.First(r => r.Id == role.RoleId).Name;
    }

Code for Creating Roles Write these lines in protected override void Seed(RoleBasedSecurity.Models.ApplicationDbContext context) in cofiguration.cs

    if (!context.Roles.Any(r => r.Name == "User"))
    {
        var store = new RoleStore<IdentityRole>(context);
        var manager = new RoleManager<IdentityRole>(store);
        var role = new IdentityRole { Name = "User" };

        manager.Create(role);
    }

Code for attaching users to role Write these lines in protected override void Seed(RoleBasedSecurity.Models.ApplicationDbContext context) in cofiguration.cs

    if (!context.Users.Any(u => u.UserName == "[email protected]"))
    {
        var store = new UserStore<ApplicationUser>(context);
        var manager = new UserManager<ApplicationUser>(store);
        var user = new ApplicationUser { UserName = "[email protected]", Email = "[email protected]" };
        manager.Create(user, "password");
        manager.AddToRole(user.Id, "Admin");
    }

To bring the roles for specific user you have to write this code.

ApplicationUser user = UserManager.FindByName(model.UserName);
string userId = user != null ? user.Id : null;
var roles = userId != null ? UserManager.GetRoles(userId) : null;
if (roles != null)
{
    foreach (var item in roles)
    {
        //Assign user roles
        UserManager.AddToRole(userId, item);
    }
}

and to get All the Roles do this

    ApplicationDbContext context = new ApplicationDbContext();
    var roles = context.Roles;

Upvotes: 1

Related Questions