Add User Roles on Registration (Forms Authenticati

2019-03-22 03:35发布

I am developing an MVC 3 project and want to add a user to a role when they are registered, using Forms Authentication. So I'd like to create some check boxes, or a drop down list showing the roles, which are selected and the user is assigned to the role as they are registered.

I have this code so far, which works:

    public ActionResult Register()
    {
        ViewData["roleName"] = new SelectList(Roles.GetAllRoles(), "roleName");
        return View();
    }

And in the view I have:

<label for="roleName">Select Role:</label>
@Html.DropDownList("roleName")
@Html.ValidationMessage("roleName")

This is HttpPost section of the controller, and this is the part that I don't know what to code:

    [HttpPost]
    public ActionResult Register(RegisterModel model)
    {
        if (ModelState.IsValid)
        {
            // Attempt to register the user
            MembershipCreateStatus createStatus;
            Membership.CreateUser(model.UserName, model.Password, model.Email, null, null, true, null, out createStatus);

            if (createStatus == MembershipCreateStatus.Success)
            {
                FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
                return RedirectToAction("Index", "Home");
            }
            else
            {
                ModelState.AddModelError("", ErrorCodeToString(createStatus));
            }
        }

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

So, all the roles do show up in the view. All I need to know is what to add to the HttpPost section to get this working.

Thanks a lot, Amy

1条回答
Viruses.
2楼-- · 2019-03-22 04:21
if (createStatus == MembershipCreateStatus.Success)
            {
                Roles.AddUserToRole(model.UserName, "RoleName");
                FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
                return RedirectToAction("Index", "Home");
            }

Try this. It's should work

查看更多
登录 后发表回答