asp.net-mvc 没有具有键“xxx”的“IEnumerable<SelectListItem>”类型的 ViewData 项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2849341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:18:52  来源:igfitidea点击:

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'xxx'

asp.net-mvcienumerabledrop-down-menuviewdataselectlist

提问by Jimbo

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.

在 Stack Overflow 上有几篇关于这个的帖子,但没有一个答案似乎可以解决我目前的情况。

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:

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

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'.

没有键为“submarket_0”的“IEnumerable”类型的 ViewData 项。

采纳答案by Jimbo

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

好的,所以答案来自有关此问题的其他一些帖子,它是:

If your ViewDatacontains a SelectListwith the same name as your DropDownListi.e. "submarket_0", the Html helper will automatically populate your DropDownListwith that data if you don't specify the 2nd parameterwhich in this case is the source SelectList.

如果您ViewData包含一个SelectList与您的DropDownList“submarket_0”同名的DropDownList如果您没有指定第二个参数(在这种情况下是源 SelectList),Html 助手将自动使用该数据填充您。

What happened with my error was:

我的错误发生了什么:

Because the table containing the drop down lists was in a partial view and the ViewDatahad been changed and no longer contained the SelectListI 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 :)

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

Please correct me if im wrong

如果我错了,请纠正我

回答by hawkke

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:

老问题,但这是对问题的另一种解释。即使您有强类型视图并且没有使用 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;
}

So if you have something like:

所以如果你有类似的东西:

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

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

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

并且Model.DropDownData为空,MVC 会在您的 ViewData 中查找命名的内容MyList,如果 ViewData 中没有具有该名称的对象,则会引发错误。

回答by Peto

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"".

在您的情况下,它应该说“没有具有键“Submarkets”的“IEnumerable”类型的 ViewData 项目”。

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").

我发布这个答案是因为我想说寻找这个错误的人,就像我一样,问题在于它没有找到 IENumerable,而是在它应该寻找它的 var 中(在这种情况下为“子市场”),不在错误显示的那个 ("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)

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

Hope this helps!

希望这可以帮助!

回答by rakesh

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

问题是因为回发发生在提交按钮点击。因此,在提交数据时再次点击提交数据,然后再返回 View()

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

回答by MovGP0

Check the Namespace.

检查命名空间。

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

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

回答by Morteza

This is OK too; For example:
==> In "NumberController" file:

这也可以;例如:
==> 在“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();
}

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

==> 在视图文件 (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'.

没有键为“OperatorId”的“IEnumerable”类型的 ViewData 项。

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

* 所以请确保这些陈述的存在。*

回答by Thuy

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.

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

回答by Mohammed Sabbir

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

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

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

change to

改成

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

Now works fine.

现在工作正常。

回答by MKS

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.

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

回答by IndieTech Solutions

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 :

我明确地想使用 Mvc,所以我将其声明为:

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