我试图修改样板帐户注册视图,以包含所有可用用户角色的下拉列表。目前,列表将正确显示,但当我尝试注册新用户时,模型状态无效。
以下是该模型的相关部分:
public class RegisterModel
{
[Required]
[Display(Name = "User name")]
public string UserName { get; set; }
[Display(Name = "Role")]
public SelectListItem Role { get; set; }
[Required]
[Display(Name = "Roles")]
public List<SelectListItem> Roles { get; set; }
[Required]
[DataType(DataType.EmailAddress)]
[Display(Name = "Email address")]
public string Email { get; set; }
...
以下是控制器的相关部分:
[HttpGet]
public ActionResult Register()
{
RegisterModel initmodel = new RegisterModel();
initmodel.Roles = new List<SelectListItem>();
foreach (string role in Roles.GetAllRoles())
{
SelectListItem item = new SelectListItem();
item.Text = role;
item.Value = role;
initmodel.Roles.Add(item);
}
return View(initmodel);
}
// POST: /Account/Register
[Authorize(Roles = "TelesageAdmin")]
[HttpPost]
public ActionResult Register(RegisterModel model)
{
SQWDataContext db = new SQWDataContext();
model.Roles = new List<SelectListItem>();
foreach (string role in Roles.GetAllRoles())
{
SelectListItem item = new SelectListItem();
item.Text = role;
item.Value = role;
model.Roles.Add(item);
}
if (ModelState.IsValid)
{
// Attempt to register the user
MembershipCreateStatus createStatus;
Membership.CreateUser(model.UserName, model.Password, model.Email, "question", "answer", true, null, out createStatus);
if (createStatus == MembershipCreateStatus.Success)
{
Roles.AddUserToRole(model.UserName, model.Role.Text);
FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
UserProfile newuser = new UserProfile();
newuser.UserName = model.UserName;
newuser.canEdit = true;
newuser.Role = model.Role.Text;
db.UserProfiles.InsertOnSubmit(newuser);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", ErrorCodeToString(createStatus));
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
非常感谢任何帮助!
答案 0 :(得分:1)
模型上的Role属性应该是字符串而不是SelectListItem。
当您发布表单时,它只会在“角色”名称后面发回所选下拉项的值。模型绑定器不能强制将字符串强制转换为SelectListItem,因此它只是放弃而最终导致错误。
此外,您还需要在[HttpPost]操作
中重建Roles对象