嘗試從我的下拉列表中選擇一個項目並提交時出現以下錯誤。使用IEnumerable SelectList的DropDown菜單
「System.InvalidOperationException」類型發生在 System.Web.Mvc.dll程序,但在用戶代碼附加 信息沒有處理的例外:有是有型 「IEnumerable的」無ViewData的項目鍵'RoleName'。
如果有人可以幫助我弄清楚如何解決這個錯誤,我真的很感激它,因爲我一直沒能解決它尚未被併爲停留相當長的時間,谷歌還沒有提供解決方案然而!
這是我的控制器代碼
[AllowAnonymous]
public ActionResult Index()
{
var roles = context.Roles.ToList();
return View(roles);
}
[Authorize(Roles = "canEdit")]
public ActionResult ManageUserRoles()
{
var list = context.
Roles.OrderBy(r => r.Name).ToList().Select(rr => new SelectListItem { Value = rr.Name.ToString(), Text = rr.Name }).ToList();
ViewBag.Roles = list;
return View();
}
public ActionResult RoleAddToUser(string UserName, string RoleName)
{
ApplicationUser user = context.Users.FirstOrDefault(u => u.UserName.Equals(UserName, StringComparison.CurrentCultureIgnoreCase));
if (user != null)
{
UserManager.AddToRole(user.Id, RoleName);
}
return View("ManageUserRoles");
}
這是我ManageUserRoles查看
@{
ViewBag.Title = "ManageUserRoles";
}
<h2>Manage User Roles</h2>
@Html.ActionLink("Create New Role", "Create") | @Html.ActionLink("View User Roles", "Index")
<hr />
<h2>Role Add to User</h2>
@using (Html.BeginForm("RoleAddToUser", "Roles"))
{
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<p>
User Name : @Html.TextBox("UserName")
Role Name: @Html.DropDownList("RoleName", (IEnumerable<SelectListItem>) ViewBag.Roles, "Select ...")
</p>
<input type="submit" value="Save" />
}
<hr />
你在哪裏添加角色到ViewBag? – tcrite