Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

Creating a Role

$
0
0

Hi

I am working from the ASP.NET Core template with Individual User Accounts.

And I am trying to create a new Role. My code below gives and error on the CreateAsync line...Object not set to an instance of an object.

Anyone with an easy example for adding a role ?

        private readonly RoleManager<IdentityRole> _roleManager;

        public ActionResult Index()
        {
            var roles = _roleManager.Roles.ToList();
            if (roles == null)
            {
                return View();
            }

            return View(roles);
        }


        //
        // GET: /Roles/Create
        public ActionResult Create()
        {
            return View();
        }

        //
        // POST: /Roles/Create
        [HttpPost]
        public ActionResult Create(IdentityRole roleViewModel)
        {
            if (ModelState.IsValid)
            {
                var role = new IdentityRole(roleViewModel.Name);
                _roleManager.CreateAsync(role);
                IdentityResult roleresult = await _roleManager.CreateAsync(role);
                if (!roleresult.Succeeded)
                {
                    ModelState.AddModelError("", roleresult.Errors.First());
                    return View();
                }
                return RedirectToAction("Index");
            }
            return View();
        }
    }


Viewing all articles
Browse latest Browse all 9386

Trending Articles