在registring上将用户添加到角色失败的ASP.NET MVC3

时间:2012-10-29 06:40:15

标签: c# asp.net-mvc-3 asp.net-membership asp.net-roles

我想让用户在asp.net mvc web应用程序中注册时选择自己的角色。我以前通过asp.net addministration工具添加角色。这是我在注册方法中使用的代码

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


 [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)
            {
                Roles.AddUserToRole(model.UserName, "roleName");
                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);
    }

在Register View中我得到了这段代码

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

角色是写在数据库和用户中的。但是UsersInRoles表是空的,我得到了这个异常

System.Configuration.Provider.ProviderException:找不到角色'roleName'。

有人有同样的问题吗?

1 个答案:

答案 0 :(得分:0)

您应该将roleName参数添加到Register controller action以获取用户roleName选择,或者从FormCollection中检索roleName,这里是示例 将您的注册帖子操作更改为:

        [HttpPost]
        public ActionResult Register(RegisterModel model, String roleName)
        {
            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)
                {
                    Roles.AddUserToRole(model.UserName, roleName);
                    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);
        }