asp.net-mvc 具有键“MY KEY”的 ViewData 项的类型为“System.String”,但必须为“IEnumerable<SelectListItem>”类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3393521/
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:24:22  来源:igfitidea点击:

The ViewData item that has the key 'MY KEY' is of type 'System.String' but must be of type 'IEnumerable<SelectListItem>'

asp.net-mvc

提问by JBibbs

I am trying to populate a dropdown list from a database mapped with Linq-2-SQL, using ASP.NET MVC 2, and keep getting this error.

我正在尝试使用 ASP.NET MVC 2 从用 Linq-2-SQL 映射的数据库填充下拉列表,并不断收到此错误。

I am so confused because I am declaring a variable of type IEnumerable<SelectListItem>on the second line, but the error makes me think this is not the case. I feel like this should be very simple, but I am struggling. Any help is appreciated.

我很困惑,因为我IEnumerable<SelectListItem>在第二行声明了一个类型的变量,但错误让我认为情况并非如此。我觉得这应该很简单,但我很挣扎。任何帮助表示赞赏。

Here are the interesting bits of my controller:

这是我的控制器的有趣部分:

public ActionResult Create()
{
    var db = new DB();
    IEnumerable<SelectListItem> basetypes = db.Basetypes.Select(
        b => new SelectListItem { Value = b.basetype, Text = b.basetype });
    ViewData["basetype"] = basetypes;
    return View();
}

And here are the interesting bits of my view:

以下是我观点中有趣的部分:

<div class="editor-label">
   <%: Html.LabelFor(model => model.basetype) %>
</div>
<div class="editor-field">
   <%: Html.DropDownList("basetype") %>
   <%: Html.ValidationMessageFor(model => model.basetype) %>
</div>

Here is the POST action when submitting the Form

这是提交表单时的 POST 操作

// POST: /Meals/Create
[HttpPost]
public ActionResult Create(Meal meal)
{
    if (ModelState.IsValid)
    {
        try
        {
            // TODO: Add insert logic here
            var db = new DB();
            db.Meals.InsertOnSubmit(meal);
            db.SubmitChanges();
            return RedirectToAction("Index");
        }
        catch
        {
            return View(meal);
        }
    }
    else
    {
        return View(meal);
    }
}

Thanks.

谢谢。

回答by Peto

I had same problem, and finally I got the answer...

我有同样的问题,最后我得到了答案......

The problem is that in the POST action, after submitting the form, the ModelState is not valid, or it's catching an error in try/catch, so the View is returned. But this time the View has not the ViewData["basetype"]correctly set.

问题是在POST操作中,提交表单后,ModelState无效,或者在try/catch中捕获错误,因此返回View。但是这次 View 没有ViewData["basetype"]正确设置。

You need to populate it again, probably with the same code used before, so repeat this:

您需要再次填充它,可能使用之前使用的相同代码,因此重复此操作:

var db = new DB();
IEnumerable<SelectListItem> basetypes = db.Basetypes.Select(
    b => new SelectListItem { Value = b.basetype, Text = b.basetype });
ViewData["basetype"] = basetypes;

before the return View(meal)in the [HttpPost]method.

之前return View(meal)[HttpPost]方法。

exactly this will solve your problem:

正是这将解决您的问题:

[HttpPost]
public ActionResult Create(Meal meal)
{
    if (ModelState.IsValid)
    {
        try
        {
            // TODO: Add insert logic here
            var db = new DB();
            db.Meals.InsertOnSubmit(meal);
            db.SubmitChanges();
            return RedirectToAction("Index");
        }
        catch
        {
            var db = new DB();
            IEnumerable<SelectListItem> basetypes = db.Basetypes.Select(
               b => new SelectListItem { Value = b.basetype, Text = b.basetype });
            ViewData["basetype"] = basetypes;
            return View(meal);
        }
    }
    else
    {
        var db = new DB();
        IEnumerable<SelectListItem> basetypes = db.Basetypes.Select(
            b => new SelectListItem { Value = b.basetype, Text = b.basetype });
        ViewData["basetype"] = basetypes;
        return View(meal);
    }
}

I know this question is very old, but I came here today with the same problem, so other could come here later...

我知道这个问题很老了,但我今天带着同样的问题来到这里,所以其他人可以稍后来这里......

回答by Ben

You will receive this error if the SelectList is null.

如果 SelectList 为空,您将收到此错误。

回答by Michael

I've just come across this issue and this article helped me through it - http://odetocode.com/Blogs/scott/archive/2010/01/18/drop-down-lists-and-asp-net-mvc.aspx

我刚刚遇到了这个问题,这篇文章帮助我解决了这个问题 - http://odetocode.com/Blogs/scott/archive/2010/01/18/drop-down-lists-and-asp-net-mvc。 aspx

The most likely cause it that your collection is repopulated after the po

最有可能的原因是您的收藏在 po 之后重新填充

回答by sxyplex

For future readers, if you are using razor, try to change type of selectlist item from List to IEnumerable.

对于未来的读者,如果您正在使用 razor,请尝试将选择列表项的类型从 List 更改为 IEnumerable。

From

@Html.DropDownListFor(m => m.id, ViewBag.SomeList as List<SelectListItem>)

To

@Html.DropDownListFor(m => m.id, ViewBag.SomeList as IEnumerable<SelectListItem>)

回答by Ray Chung

I got same error today and my solution is to make model "valid".

我今天遇到了同样的错误,我的解决方案是使模型“有效”。

In my case, after user submit by clicking "save", I got model state: invalid if user key-in "0", but model state will be valid if user key-in "0.0".

就我而言,在用户通过单击“保存”提交后,我得到模型状态:如果用户键入“0”则无效,但如果用户键入“0.0”则模型状态将有效。

So I override "IsValid" method to return true even user key-in "0".

所以我覆盖了“IsValid”方法,即使用户键入“0”也返回true。

Hope it helps.

希望能帮助到你。

回答by Mariano Gianni

To future readers,

对于未来的读者,

I came across with the problem today and couldn′t fix it. It turned to be really simple after all. I was working with a table + view. When I updated the table (added a few colums) I forgot to update (drop and recreate) the view, which caused the problem for me. Hope it helps somebody.

我今天遇到了这个问题,无法解决。毕竟它变得非常简单。我正在使用表格 + 视图。当我更新表(添加了一些列)时,我忘记更新(删除并重新创建)视图,这给我带来了问题。希望它可以帮助某人。

回答by Igor Zevaka

You are setting the collection as an item in ViewData dictionary and trying to retreive it as property on the model. A simple fix would be to reference it the same way as you set it:

您正在将集合设置为 ViewData 字典中的一个项目,并尝试将其作为模型的属性进行检索。一个简单的解决方法是像设置它一样引用它:

    <%var basetype = ViewData["basetype"] as IEnumerable<SelectListItem>;%>
    <div class="editor-label">
        <%: Html.Label("basetype") %>
    </div>
    <div class="editor-field">
        <%: Html.DropDownList("basetype", basetype) %>
        <%: Html.ValidationMessage("basetype") %>
    </div>

Alternatively, the below code uses a strongly typed view:

或者,以下代码使用强类型视图:

public class ViewModel {
   //Model properties
   public IEnumerable<SelectListItem> basetype {get;set;}
}

public ActionResult Create()
    {
        var db = new DB();
        IEnumerable<SelectListItem> basetypes = db.Basetypes.Select(b => new SelectListItem { Value = b.basetype, Text = b.basetype });
        return View(new ViewModel { basetype=basetypes });
    }

Then, in your strongly typed view:

然后,在您的强类型视图中:

    <div class="editor-label">
        <%: Html.LabelFor(model => model.basetype) %>
    </div>
    <div class="editor-field">
        <%: Html.DropDownListFor(model=>model.basetype) %>
        <%: Html.ValidationMessageFor(model => model.basetype) %>
    </div>

回答by CRice

Try adding a string for the name of your dropdown list as the first parameter, and get the item out of your viewdata:

尝试为下拉列表的名称添加一个字符串作为第一个参数,并从您的视图数据中获取该项目:

 <%= Html.DropDownList("SomeDropdownName", (IEnumerable<SelectListItem>)ViewData["basetype"]) %>

Here is also an extension method you can use so the dropdown list is set up in a similar style to how you have done your other controls:

这也是您可以使用的扩展方法,因此下拉列表的设置方式与您完成其他控件的方式类似:

        public static string DropDownList<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel)
        where TModel : class
    {
        string inputName = ExpressionHelper.GetInputName(expression);
        return htmlHelper.DropDownList(inputName, selectList, optionLabel);
    }

For example

例如

<%= Html.DropDownList(x => x.BaseType, (IEnumerable<SelectListItem>)ViewData["basetype"], "")%>

回答by Evgeny Levin

If you use Html.DropDownList()method - same error may occur, if your ViewData/Viewbag item not set, as @Peto answered.

如果您使用Html.DropDownList()方法 - 可能会发生同样的错误,如果您的 ViewData/Viewbag 项目未设置,如@Peto 所回答。

But it may be not set in case of controller set item correctly, but in main view you use partial viw call with new ViewDataDictionary values.

但在控制器设置项正确的情况下,它可能不会设置,但在主视图中,您使用具有新 ViewDataDictionary 值的局部视图调用。

if you have @Html.Partial("Partianame", Model,new ViewDataDictionary() { /* ... */ })then your partial view will not see ViewDataand ViewBagdata, remove new ViewDataDictionary()parameter

如果你有@Html.Partial("Partianame", Model,new ViewDataDictionary() { /* ... */ })那么你的部分视图将看不到ViewDataViewBag数据,删除new ViewDataDictionary()参数