没有类型为“IEnumerable”的 ViewData 项;具有密钥“xxx”;

发布于 2024-09-02 06:57:32 字数 554 浏览 8 评论 0 原文

Stack Overflow 上有几篇关于此问题的帖子,但没有一个答案似乎可以解决我当前情况下的问题。

我有一个页面,其中有一个表格,每行都有多个文本字段和一个下拉列表。所有下拉菜单都需要使用相同的 SelectList 数据,因此我将其设置如下:

Controller

ViewData["Submarkets"] = new SelectList(submarketRep.AllOrdered(), "id", "name");

View

<%= Html.DropDownList("submarket_0", (SelectList)ViewData["Submarkets"], "(none)") %>

我在很多地方都使用了这种设置,但由于某些原因在这个特定视图中,我收到错误:

不存在具有键“submarket_0”的“IEnumerable”类型的 ViewData 项。

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.

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:

Controller

ViewData["Submarkets"] = new SelectList(submarketRep.AllOrdered(), "id", "name");

View

<%= 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:

There is no ViewData item of type 'IEnumerable' that has the key 'submarket_0'.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

二货你真萌 2024-09-09 06:57:34

原因并不是违反语法,而是对象的使用不当。
ViewData、ViewBag 等对象的生命周期视图生命周期比会话中短。前者定义的数据将在请求-响应后丢失(如果尝试在请求-响应后访问,则会出现异常)。所以前者适合在 View 和 View 之间传递数据。控制器而后者用于存储临时数据。临时数据应存储在会话中,以便可以多次访问。

The cause isn't contrary to syntax rather than inappropriate usage of objects.
Life Cycle of objects in ViewData, ViewBag, & View Life Cycle is shorter than in the session. Data defined in the formers will be lost after a request-response(if try to access after a request-response, you will get exceptions). So the formers are appropriate for passing data between View & Controller while the latter for storing temporary data. The temporary data should store in the session so that can be accessed many times.

东走西顾 2024-09-09 06:57:34

就我而言,命名空间存在冲突,我有:

using System.Web.Mvc;

并且

using System.Collections.Generic;

我明确想要使用 Mvc 命名空间,因此我将其声明为:

new System.Web.Mvc.SelectList(...)

In my case there was a conflict in the namespaces , I have:

using System.Web.Mvc;

and

using System.Collections.Generic;

I explicitly want to use the Mvc one so I declared it as :

new System.Web.Mvc.SelectList(...)
单身狗的梦 2024-09-09 06:57:33

好的,答案是从有关此问题的其他一些帖子得出的,它是:

如果您的 ViewData 包含一个与您的 DropDownList 同名的 SelectList code> 即“submarket_0”,如果您不指定第二个参数(在本例中为源 SelectList),Html 帮助程序将自动使用该数据填充您的 DropDownList

我的错误发生的原因是:

因为包含下拉列表的表位于部分视图中,并且 ViewData 已更改并且不再包含我引用的 SelectList , HtmlHelper(而不是抛出错误)尝试在 ViewData 中查找名为“submarket_0”的 SelectList(GRRRR!!!),但它仍然找不到,然后抛出一个错误:)

请如果我错了请纠正我

Ok, so the answer was derived from some other posts about this problem and it is:

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.

What happened with my error was:

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 :)

Please correct me if im wrong

爱*していゐ 2024-09-09 06:57:33

老问题,但这是问题的另一种解释。即使您有强类型视图并且没有使用 ViewData 创建下拉列表,您也会收到此错误。当您查看 MVC 源

// If we got a null selectList, try to use ViewData to get the list of items.
if (selectList == null)
{
    selectList = htmlHelper.GetSelectData(name);
    usedViewData = true;
}

因此,如果您有类似以下内容:

@Html.DropDownList("MyList", Model.DropDownData, "")

Model.DropDownData< /code> 为 null,MVC 会在 ViewData 中查找名为 MyList 的内容,如果 ViewData 中没有具有该名称的对象,则会抛出错误。

Old question, but here's another explanation of the problem. You'll get this error even if you have strongly typed views and aren't using ViewData to create your dropdown list. The reason for the error can becomes clear when you look at the MVC source:

// If we got a null selectList, try to use ViewData to get the list of items.
if (selectList == null)
{
    selectList = htmlHelper.GetSelectData(name);
    usedViewData = true;
}

So if you have something like:

@Html.DropDownList("MyList", Model.DropDownData, "")

And Model.DropDownData is null, MVC looks through your ViewData for something named MyList and throws an error if there's no object in ViewData with that name.

嗼ふ静 2024-09-09 06:57:33

我遇到了同样的错误,我认为问题是错误文本令人困惑,因为它给出了错误的键名称。

在你的情况下,它应该说“没有类型为‘IEnumerable’的 ViewData 项具有键‘子市场’”。

我的错误是视图代码(您的“子市场”)中的拼写错误,但错误文本让我发疯。

我发布这个答案是因为我想说人们在寻找这个错误,就像我一样,问题是它没有找到 IEnumerable,而是在它应该寻找它的 var 中(此中的“子市场”)情况),而不是错误显示的情况(“submarket_0”)。

接受的答案非常有趣,但正如您所说,如果您不指定第二个参数,则应用约定,在本例中指定了第二个参数,但未找到 var (在您的情况下,因为 viewdata 没有它,在我的情况下,因为我拼错了变量名称)

希望这有帮助!

I had same error, I think the problem is that the error text is confusing, because its giving a false key name.

In your case It should say "There is no ViewData item of type 'IEnumerable' that has the key "Submarkets"".

My error was a misspelling in the view code (your "Submarkets"), but the error text made me go crazy.

I post this answer because I want to say people looking for this error, like I was, that the problem is that its not finding the IENumerable, but in the var that its supposed to look for it ("Submarkets" in this case), not in the one showed in error ("submarket_0").

Accepted answer is very interesting, but as you said the convention is applied if you dont specify the 2nd parameter, in this case it was specified, but the var was not found (in your case because the viewdata had not it, in my case because I misspelled the var name)

Hope this helps!

野心澎湃 2024-09-09 06:57:33

问题是因为点击提交按钮时发生回发。
因此,在提交时发布数据时单击
返回 View() 之前再次写入

ViewData["Submarkets"] = new SelectList(submarketRep.AllOrdered(), "id", "name");

The problem is because of post back happens on submit button click.
So while posting data on submit click
again write before returning View()

ViewData["Submarkets"] = new SelectList(submarketRep.AllOrdered(), "id", "name");
活雷疯 2024-09-09 06:57:33

检查命名空间。

您可以在控制器中分配System.Web.Webpages.Html.SelectListItem,而不是System.Web.Mvc.SelectListItem

Check the Namespace.

You might assign System.Web.Webpages.Html.SelectListItem in the Controller, instead of System.Web.Mvc.SelectListItem.

偏闹i 2024-09-09 06:57:33

这也可以;例如:

==>在“NumberController”文件中:

public ActionResult Create([Bind(Include = "NumberId,Number1,Number2,OperatorId")] Number number)
{
    if (ModelState.IsValid)
    {
        ...
        ...
        return RedirectToAction("Index");
    }
    ViewBag.OperatorId = new SelectList(db.Operators, "OperatorId", 
                                "OperatorSign", number.OperatorId);                
    return View();
}

==>在视图文件 (Create.cshtml) 中:

<div class="form-group">
    @Html.LabelFor(model => model.Number1, htmlAttributes: new { @class = 
                   "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.Number1, new { htmlAttributes = new { 
                        @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Number1, "", new { @class = 
                                   "text-danger" })
    </div>
</div>

删除此语句:

ViewBag.OperatorId = new SelectList(db.Operators, "OperatorId", "OperatorSign", number.OperatorId);

现在如果我们从以下语句后面

return View();

看到此错误:

(在我们的控制器中):我们将 没有具有键“OperatorId”的“IEnumerable”类型的 ViewData 项。

* 因此请确保这些语句存在。 *

This is OK too; For example:

==> In "NumberController" file:

public ActionResult Create([Bind(Include = "NumberId,Number1,Number2,OperatorId")] Number number)
{
    if (ModelState.IsValid)
    {
        ...
        ...
        return RedirectToAction("Index");
    }
    ViewBag.OperatorId = new SelectList(db.Operators, "OperatorId", 
                                "OperatorSign", number.OperatorId);                
    return View();
}

==> In View file (Create.cshtml):

<div class="form-group">
    @Html.LabelFor(model => model.Number1, htmlAttributes: new { @class = 
                   "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.Number1, new { htmlAttributes = new { 
                        @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Number1, "", new { @class = 
                                   "text-danger" })
    </div>
</div>

Now if we remove this statement:

ViewBag.OperatorId = new SelectList(db.Operators, "OperatorId", "OperatorSign", number.OperatorId);

from back of the following statement (in our controller) :

return View();

we will see this error:

There is no ViewData item of type 'IEnumerable' that has the key 'OperatorId'.

* So be sure of the existing of these statements. *

城歌 2024-09-09 06:57:33

对我来说,当我将新行保存到数据库但字段为空时,出现了导致此错误的问题。在数据库表设计中,该字段是NOT NULL。因此,当我尝试保存非空字段具有空值的新行时,Visual Studio 抛出此错误。因此,我确保为该字段分配了一个值,并且问题得到了解决。

For me, the problem that caused this error arose when I was saving a new row to the database, but a field was null. In the database table design, that field is NOT NULL. So when I tried to save a new row with a null value for not-null field, Visual Studio threw this error. Thus, I made sure that the field was assigned a value, and the problem was fixed.

箹锭⒈辈孓 2024-09-09 06:57:33

就我而言,我发现我错误地将 post 方法设置为私有。私有更改为公共后。

[HttpPost]
private async Task<ActionResult> OnPostRemoveForecasting(){}

更改为

[HttpPost]
public async Task<ActionResult> OnPostRemoveForecasting(){}

“现在”效果很好。

In my case, I found that I set the post method as private mistakenly. after changing private to public.

[HttpPost]
private async Task<ActionResult> OnPostRemoveForecasting(){}

change to

[HttpPost]
public async Task<ActionResult> OnPostRemoveForecasting(){}

Now works fine.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文