C# MVC下拉列表 - 没有具有键''的类型为“IEnumerable<SelectListItem>”的ViewData项

3

我刚试图通过将DropDownList添加到home/contact.cshtml来扩展以前的项目。

我的问题是,当在Firefox中加载页面时,我不停地收到以下错误:

错误:发生了类型为'System.InvalidOperationException'的异常,但未在用户代码中处理。没有数据项为“displayGraph”的类型'IEnumerable'。

我在另一个页面上有另一个下拉列表,它可以正常工作(使用相同的方法)。如果我将相同的代码复制到新项目中,则可以正常工作。请问有人能告诉我可能会导致这种情况吗?

contact.cshtml - 代码片段

    @using (Html.BeginForm("Index", "Home", FormMethod.Get))
    {
        <p>
            Filter By: @Html.DropDownList("displayGraph","Select a Graph")                
            <input type="submit" value="Filter" />
        </p>            
    }

HomeController - 代码片段

    public ActionResult Index()
    {
        string chart1 = "Num Each Model Processed", chart2 = "Another chart to be assigned";
        var GraphLst = new List<string> { chart1, chart1 };
        ViewBag.displayGraph = new SelectList(GraphLst);

        string userName = User.Identity.Name;
        return View();
    }

Graphdropdownmodel - 代码片段

   namespace TestSolution.Models
 {
      public class GraphDropdownModel
    {   
    public IEnumerable<SelectListItem> Graph{ get; set; }
    }
    public class GraphDBContext : DbContext
    {
    public DbSet<GraphDropdownModel> Graphs { get; set; }
    }
 }

1
以上代码对我来说可以直接使用 https://dotnetfiddle.net/JR3iFy - hutchonoid
2个回答

3
尝试使用@Html.DropDownListFor。
    @Html.DropDownListFor(model => model.value, (SelectList)ViewBag.displayGraph)

好的,我认为上面已经指出了缺少什么。我刚刚创建了一个模型,并将其添加到上面。感谢您的输入,Wozone,但我无法选择model => model.Graph,我想这可能与我的模型配置不正确有关? - Baggerz
对于DropDownListFor,第一个属性是将包含用户选择的选项的变量。通常这是图表的ID。您可以更改模型以包括图表ID。假设存在ID。 - WoZoNe

1
问题在于ViewBag是一个动态属性,而DropDownList无法确定它必须将实际类型(即SelectList)转换为IEnuerable<SelectListItem>以使转换运算符起作用。

然而,这可能是一件好事,因为即使您设法让它工作,您也会遇到麻烦。一旦您尝试将数据提交回服务器,MVC模型绑定程序就会感到困惑,因为您现在有了一个名为displayGraphModelState项目,其类型为SelectList,而您还要发布名称为displayGraph的字符串值。

这就是为什么使用DropDownListFor()更好(或者至少使用带有单独属性名称和集合列表的DropDownList()重载)。始终将所选属性命名不同于用于填充下拉列表的集合,这将为您节省很多麻烦。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接