2015-12-21 45 views
0

嘗試從我的下拉列表中選擇一個項目並提交時出現以下錯誤。使用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 /> 
+0

你在哪裏添加角色到ViewBag? – tcrite

回答

0

問題是(我假設)您正在從您的ActionResult RoleAddToUser而不是ManageUserRoles訪問View(「ManageUserRoles」)。所以ViewBag不存在。

return View("ManageUserRoles"); 

開始渲染視圖。然而,在視圖中,您需要ViewBag.Roles的下拉列表...但是...您在哪裏設置數據?拋出此異常是因爲ViewBag.Roles不存在。

如果要在返回視圖之前運行ActionResult ManageUserRoles,則必須調用重定向。

return RedirectToAction("ManageUserRoles"); 

如果你想渲染視圖,而不在該方法中執行代碼,你必須創建在RoleAddToUser ViewBag.Roles。請注意,ViewBag數據在每次請求後都會被刪除。

+0

非常感謝您的幫助@Ademar – LucyJane

0

驗證模型(它的域模型或其他一些視圖模型是否)有字符串類型的字段名爲「RoleName」,這需要匹配DropDownList調用的第一個參數,以便頁面知道在表單提交中將數據發回的變量。

+0

我檢查了我的模型,並且該字段被稱爲Name而不是RoleName,但是在將RoleName的所有引用更改爲Name之後,我仍然得到相同的錯誤 – LucyJane