我对 asp.net-mvc 下拉列表做错了什么?
我在我的 create.aspx 之一中使用了一个下拉列表,但它似乎不起作用...
public IEnumerable<SelectListItem> FindAllMeasurements()
{
var mesurements = from mt in db.MeasurementTypes
select new SelectListItem
{
Value = mt.Id.ToString(),
Text= mt.Name
};
return mesurements;
}
而我的控制器
public ActionResult Create()
{
var mesurementTypes = consRepository.FindAllMeasurements().AsEnumerable();
ViewData["MeasurementType"] = new SelectList(mesurementTypes,"Id","Name");
return View();
}
和我的 create.aspx 有这个,
<p>
<label for="MeasurementTypeId">MeasurementType:</label>
<%= Html.DropDownList("MeasurementType")%>
<%= Html.ValidationMessage("MeasurementTypeId", "*") %>
</p>
当我执行这个时,我得到了这些错误,
DataBinding: 'System.Web.Mvc.SelectListItem' does not contain a
property with the name 'Id'.
I use a dropdownlist in one of my create.aspx but it some how doesnt seem to work...
public IEnumerable<SelectListItem> FindAllMeasurements()
{
var mesurements = from mt in db.MeasurementTypes
select new SelectListItem
{
Value = mt.Id.ToString(),
Text= mt.Name
};
return mesurements;
}
and my controller,
public ActionResult Create()
{
var mesurementTypes = consRepository.FindAllMeasurements().AsEnumerable();
ViewData["MeasurementType"] = new SelectList(mesurementTypes,"Id","Name");
return View();
}
and my create.aspx has this,
<p>
<label for="MeasurementTypeId">MeasurementType:</label>
<%= Html.DropDownList("MeasurementType")%>
<%= Html.ValidationMessage("MeasurementTypeId", "*") %>
</p>
When i execute this i got these errors,
DataBinding: 'System.Web.Mvc.SelectListItem' does not contain a
property with the name 'Id'.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在您的控制器中,您正在从
IEnumerable
创建一个新的SelectList
,这是不正确的,因为您已经指定了Value
和文本
属性。您有两个选择:
或者:
还有第三种也是首选的方法,使用强类型视图:
并在视图中:
In your controller you are creating a new
SelectList
fromIEnumerable<SelectListItem>
which is not correct because you've already specified theValue
andText
properties.You have two options:
or:
There's also a third and preferred way using strongly typed view:
and in the view:
正如错误消息所暗示的那样,您需要一个
IEnumerable
,而不是IEnumerable
。SelectList 的构造函数有一个采用 IEnumerable 的重载。请参阅 .net MVC、SelectLists 和 LINQ
As the error message implies, you need an
IEnumerable<SelectList>
, not anIEnumerable<Materials>
.The constructor for SelectList has an overload that takes an IEnumerable. See .net MVC, SelectLists, and LINQ