項目中的某個頁面,在訪問時出現以下錯誤:
不存在具有鍵“xxxId”的“IEnumerable<SelectListItem>”類型的 ViewData 項
具體的場景說明如下:
一個編輯頁,其中某下拉控件綁定值為來自model對象中的一個List<SelectListItem>集合屬性。具體看下面:
Ⅰ、前端視圖頁面的代碼
@Html.DropDownListFor(p => p.SubitemTypeId,(Model.SubitemTypeList as List<SelectListItem>), new { @class = "form-control" })
Ⅱ、后端控制器中返回視圖的action
public ActionResult EditSubitem(long? id) { var entObj = new SubitemModel();//初始化基礎數據 if (id!=null&&id!=0) { entObj = _SubitemAppService.GetSubitem(id.Value); } entObj.SubitemTypeList = _SubitemTypeAppService.SubitemTypeList();//返回List<SelectListItem>的集合 return View(entObj); }
1)當_SubitemTypeAppService.SubitemTypeList()返回集合不為空時,訪問頁面下拉控件不會報錯;
2)當_SubitemTypeAppService.SubitemTypeList()返回集合為空時,訪問頁面時,下拉控件會報文章開頭的錯
原因:當返回為空值時,則Model.SubitemTypeList為null值,當然不能轉化為 List<SelectListItem>下拉項。
處理方式為修改頁面綁定的值的方式,當為null時增加一個為空的默認項
@Html.DropDownListFor(p => p.SubitemTypeId,
Model.SubitemTypeList==null?new List<SelectListItem> { new SelectListItem { Text="無選項",Value=""} } : (Model.SubitemTypeList as List<SelectListItem>), new { @class = "form-control" })
在網上查找時,發現還有一種情況也會出現以上報錯:http://bbs.csdn.net/topics/380095463
