【发布时间】:2016-05-11 21:34:20
【问题描述】:
我对 asp.net MVC 很陌生。我正在编写一个允许系统管理员查看/编辑/添加服务器列表的应用程序。我已经有了服务器的数据库,所以我先用数据库来创建实体框架模型。
从这里开始,我使用 Visual Studios 自动生成来创建几个视图。第一个工作神奇,真正向我展示了这个框架的力量,因为它解决了所有外键查找,而我在连接表方面没有任何工作。
第二个,我使用 Visual Studio 生成了一个创建视图。然后我创建了一个 Create [HttpGet] 函数,它只返回一个新对象。但是,当我单击此链接时 - 应用程序在这些代码行上爆炸:
<div class="form-group">
@Html.LabelFor(model => model.ServerOS, "ServerOS", htmlAttributes: new { @class = "control-label col-md-2" })
<div class="col-md-10">
@Html.DropDownList("ServerOS", null, htmlAttributes: new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.ServerOS, "", new { @class = "text-danger" })
</div>
</div>
以上代码是我为模型创建视图时由 Visual Studio 生成的。它给了我错误:
An exception of type 'System.InvalidOperationException' occurred in
System.Web.Mvc.dll but was not handled in user code
Additional information: There is no ViewData item of type
'IEnumerable<SelectListItem>' that has the key 'ServerOS'.
视图的动作如下:
[HttpGet]
public ActionResult Create()
{
return View("Create",
new SQLServer());
}
我应该注意到 ServerOS 是数据库中的外键。我对 HTML 也很陌生,所以我很难阅读它在做什么。
【问题讨论】:
-
因为
ServerOS不是IEnumerable<SelectListItem>您需要在控制器中生成SelectList并将其传递给视图(下拉列表需要2 个值-要绑定的属性(选定的值) 和选项集合的属性(请参阅this answer 来解释) -
@StephenMuecke 非常感谢!我会用答案编辑我的帖子,除非你想发布你的答案。
-
添加您自己的答案需要付费(使其成为答案而不是对问题的编辑,以便您可以接受并关闭它)
标签: c# asp.net-mvc