没有“IEnumerable<SelectListItem>"类型的 ViewData 项有键'xxx' [英] There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'xxx'
问题描述
在 Stack Overflow 上有几篇关于这个的帖子,但没有一个答案似乎可以解决我目前的情况.
There are a couple of posts about this on Stack Overflow but none with an answer that seem to fix the problem in my current situation.
我有一个带有表格的页面,每一行都有许多文本字段和一个下拉列表.所有下拉菜单都需要使用相同的 SelectList 数据,因此我将其设置如下:
I have a page with a table in it, each row has a number of text fields and a dropdown. All the dropdowns need to use the same SelectList data so I have set it up as follows:
控制器
ViewData["Submarkets"] = new SelectList(submarketRep.AllOrdered(), "id", "name");
查看
<%= Html.DropDownList("submarket_0", (SelectList)ViewData["Submarkets"], "(none)") %>
我在很多地方都使用过这个设置,但由于某种原因在这个特定的视图中我得到了错误:
I have used exactly this setup in many places, but for some reason in this particular view I get the error:
没有键为submarket_0"的IEnumerable"类型的 ViewData 项.
推荐答案
好的,所以答案来自其他一些关于这个问题的帖子,它是:
Ok, so the answer was derived from some other posts about this problem and it is:
如果您的 ViewData
包含与您的 DropDownList
同名的 SelectList
,即submarket_0",Html 助手将自动填充您的 DropDownList
使用该数据如果您不指定第二个参数,在本例中为源 SelectList.
If your ViewData
contains a SelectList
with the same name as your DropDownList
i.e. "submarket_0", the Html helper will automatically populate your DropDownList
with that data if you don't specify the 2nd parameter which in this case is the source SelectList.
我的错误发生了什么:
因为包含下拉列表的表格在局部视图中并且 ViewData
已更改并且不再包含我引用的 SelectList
,HtmlHelper
(而不是抛出错误)试图在它仍然找不到的 ViewData (GRRRR!!!) 中找到名为submarket_0"的 SelectList,然后抛出一个错误:)
Because the table containing the drop down lists was in a partial view and the ViewData
had been changed and no longer contained the SelectList
I had referenced, the HtmlHelper
(instead of throwing an error) tried to find the SelectList called "submarket_0" in the ViewData (GRRRR!!!) which it STILL couldnt find, and then threw an error on that :)
如果我错了请纠正我
这篇关于没有“IEnumerable<SelectListItem>"类型的 ViewData 项有键'xxx'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!