あまりにも長い間これにいました!次の問題に関するアドバイス...
追加されたコード:
モデル:AccountModels.cs
[Required]
[Display(Name = "Select role: ")]
public String Role { get; set; }
コントローラー:AccountController.cs
// GET: /Account/Register
public ActionResult Register()
{
List<SelectListItem> list = new List<SelectListItem>();
SelectListItem item;
foreach (String role in Roles.GetAllRoles())
{
item = new SelectListItem { Text = role, Value = role };
list.Add(item);
}
ViewBag.roleList = (IEnumerable<SelectListItem>)list;
return View();
}
[HTTpPost]にも
if (createStatus == MembershipCreateStatus.Success)
{
Roles.AddUserToRole(model.UserName, model.Role);
MailClient.SendWelcome(model.Email);
FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);
return RedirectToAction("Create", "Customers");
}
表示:Register.cshtml
<div class="editor-label">
@Html.LabelFor(m => m.Role)
</div>
<div class="editor-field">
@Html.DropDownListFor(m => m.Role, ViewBag.roleList as IEnumerable<SelectListItem>)
コードは機能し、ユーザーが役割を選択できるようにしますが、ユーザーが新しいアカウントを作成するときに検証ルールに違反すると、崩壊します。
例:パスワードが通常一致しない場合、検証が開始されますが、新しいコードが追加されたため、アプリケーションがクラッシュします。
エラーを作成するコード:
@Html.DropDownListFor(m => m.Role, ViewBag.roleList as IEnumerable<SelectListItem>)
エラーコード
キー「Role」を持つViewDataアイテムのタイプは「System.String」ですが、タイプは「IEnumerable」である必要があります。