0

我喜欢让用户在注册 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);
    }

在注册视图中我得到了这个代码

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

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

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

有没有人有同样的问题?

4

1 回答 1

0

您应该将角色名称参数添加到注册控制器操作以获取用户角色名称选择,或从 FormCollection 中检索角色名称,这是示例将您的注册发布操作更改为:

        [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);
        }
于 2012-10-29T10:49:25.083 回答