我刚刚尝试通过在home/contact.cshtml上添加下拉列表来扩展以前的项目。
我的问题是我在firefox中加载页面时一直收到以下错误
错误:类型为"System"的异常。在System.Web.Mvc.dll中发生了InvalidOperationException,但没有在用户代码中处理没有'IEnumerable'类型的ViewData项具有'displayGraph'键
我有另一个下拉列表在另一个页面,工作正常(相同的方法),如果我复制相同的代码到一个新的项目,它工作正常,谁能告诉我什么可能导致这?
接触。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; }
}
}
尝试使用@Html。DropDownListFor
@Html.DropDownListFor(model => model.value, (SelectList)ViewBag.displayGraph)
这里的问题是ViewBag
是一个动态属性,而DropDownList
不能弄清楚它必须将实际类型(即SelectList
)转换为IEnuerable<SelectListItem>
才能使转换操作符工作。
然而,这可能是一件好事,因为即使你真的让它工作了,你也会遇到麻烦。一旦你试图将数据发送回服务器,MVC模型绑定器就会感到困惑,因为你现在在ModelState
中有一个名为displayGraph
的项目,它的类型是SelectList
,而且你还以displayGraph
的名称发布字符串值。
这就是为什么使用DropDownListFor()
更好(或者至少使用DropDownList()
的重载,它接受单独的属性名和集合列表)。
选择的属性总是与你用来填充下拉菜单的集合不同,这将为你节省很多麻烦。