我有一个注册视图 - 只有“管理员”角色的人才能创建新用户。我正在使用标准的 VS2012 注册视图 - 但我还想添加一个下拉列表,以允许管理员选择新用户所属的角色。
当表单被回发时,使用控制器 Register(RegisterModel 模型) - 我如何使用选定的角色获取下拉列表并在此处填充:
Roles.AddUserToRole(model.UserName, XXXXXXXXXX);
看法:
<fieldset>
<legend>Registration Form</legend>
<ol>
<li>
@Html.LabelFor(m => m.UserName)
@Html.TextBoxFor(m => m.UserName)
</li>
<li>
@Html.LabelFor(m => m.Email)
@Html.TextBoxFor(m => m.Email)
</li>
<li>
@Html.LabelFor(m => m.Password)
@Html.PasswordFor(m => m.Password)
</li>
<li>
@Html.LabelFor(m => m.ConfirmPassword)
@Html.PasswordFor(m => m.ConfirmPassword)
</li>
<li>
Type of user:
@Html.DropDownList("roleName")
</li>
</ol>
<input type="submit" value="Register" />
</fieldset>
控制器:
//
// POST: /Account/Register
[Authorize(Roles = "admin")]
[HttpPost]
public ActionResult Register(RegisterModel model)
{
if (ModelState.IsValid)
{
// Attempt to register the user
MembershipCreateStatus createStatus;
Membership.CreateUser(model.UserName, model.Password, model.Email, passwordQuestion: null, passwordAnswer: null, isApproved: true, providerUserKey: null, status: out createStatus);
if (createStatus == MembershipCreateStatus.Success)
{
// Add user to selected role
Roles.AddUserToRole(model.UserName, XXXXXXXXXX);
// Don't want to login the user - as "admin" is creating this user
// FormsAuthentication.SetAuthCookie(model.UserName, createPersistentCookie: false);
//ViewBag.created = "yes";
return RedirectToAction("UserList","Account");
}
else
{
ModelState.AddModelError("", ErrorCodeToString(createStatus));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
谢谢,
标记