具有键“MY KEY”的ViewData项的类型为“System.String”,但必须是“IEnumerable”类型。

18 浏览
0 Comments

具有键“MY KEY”的ViewData项的类型为“System.String”,但必须是“IEnumerable”类型。

我正在尝试使用Linq-2-SQL映射的数据库来填充一个下拉列表,使用ASP.NET MVC 2,但是一直在遇到这个错误。

我很困惑,因为我在第二行声明了一个类型为IEnumerable的变量,但是错误让我觉得这不是这种情况。我觉得这应该很简单,但我还是遇到了困难。感谢任何帮助。

这是我的控制器的相关部分:

public ActionResult Create()

{

var db = new DB();

IEnumerable basetypes = db.Basetypes.Select(

b => new SelectListItem { Value = b.basetype, Text = b.basetype });

ViewData["basetype"] = basetypes;

return View();

}

这是我的视图的相关部分:

<%: Html.LabelFor(model => model.basetype) %>

<%: Html.DropDownList("basetype") %>

<%: Html.ValidationMessageFor(model => model.basetype) %>

这是在提交表单时的POST操作:

[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);

}

}

谢谢。

0
0 Comments

stback, so when the form is submitted, the selected value is not retained and the collection is reloaded with the original values. This causes the ViewData item with the key 'MY KEY' to be of type 'System.String' instead of 'IEnumerable'.

To fix this issue, you can ensure that the collection is repopulated only when the form is not being submitted. One way to do this is by checking the ModelState.IsValid property before repopulating the collection. Here's an example:

if (!ModelState.IsValid)
{
    // Repopulate the collection
    ViewData["MY KEY"] = new List
    {
        new SelectListItem { Value = "1", Text = "Option 1" },
        new SelectListItem { Value = "2", Text = "Option 2" },
        new SelectListItem { Value = "3", Text = "Option 3" }
    };
}

By checking the ModelState.IsValid property, the collection will only be repopulated if there are validation errors in the form submission. This ensures that the selected value is retained and the ViewData item is of the correct type.

Additionally, you can also use the Html.DropDownListFor helper method instead of manually populating the collection in the controller. This method automatically takes care of retaining the selected value and generating the correct HTML markup for the dropdown list. Here's an example:

// In the controller
ViewData["MY KEY"] = new List
{
    new SelectListItem { Value = "1", Text = "Option 1" },
    new SelectListItem { Value = "2", Text = "Option 2" },
    new SelectListItem { Value = "3", Text = "Option 3" }
};
// In the view
@Html.DropDownListFor(model => model.SelectedOption, (IEnumerable)ViewData["MY KEY"])

Using the Html.DropDownListFor method eliminates the need to manually check the ModelState.IsValid property and repopulate the collection. It simplifies the code and ensures that the ViewData item is always of the correct type.

Overall, the most likely cause of the error message "The ViewData item that has the key 'MY KEY' is of type 'System.String' but must be of type 'IEnumerable'" is the incorrect repopulation of the collection after a postback. By following the suggested solutions, you can ensure that the selected value is retained and the ViewData item is of the correct type, resolving the issue.

0
0 Comments

原因:如果SelectList为空,则会出现此错误。这通常是在GET操作上设置SelectList,然后回发到POST操作(显然)时发生的常见错误/疏忽。当ModelState.IsValid==false时,返回模型return View(model),但在从POST返回之前未重新填充SelectList源。由于没有WebForms的ViewState,所以没有源供.DropDown帮助程序重新构建选择。每次将视图返回给客户端时,您都必须重新填充源列表,而不仅仅是在GET操作上。

解决方法:确保在每次返回视图给客户端时都重新填充SelectList源。

0
0 Comments

问题出现的原因是,在POST操作中,提交表单后,模型状态无效,或者在try/catch中捕获了错误,因此返回了View。但是这时View中没有正确设置ViewData["basetype"]。

解决方法是,在[HttpPost]方法中的return View(meal)之前,重新填充ViewData["basetype"],可以使用之前使用的相同代码来重复填充,即:

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

完整的解决方法如下:

[HttpPost]
public ActionResult Create(Meal meal)
{
    if (ModelState.IsValid)
    {
        try
        {
            // TODO: 在此处添加插入逻辑
            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);
    }
}

如果在提交之前遇到此问题,可能是因为SelectList中没有任何内容。

另外,如果在Index方法中设置了ViewBag,而实际上应该调用另一个Action方法,则也会出现此问题。

希望这篇文章能帮到其他人解决类似的问题。

0