2010-05-03 78 views
7

我用一个下拉列表中我create.aspx之一,但它的一些似乎没有怎么工作...我在做什么asp.net-mvc dropdownlist错误?

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'. 

回答

7

在你的控制器,你正在创建从IEnumerable<SelectListItem>SelectList,因为你已经指定了ValueText特性,这是不正确的。

你有两个选择:

public ActionResult Create() 
{ 
    var mesurementTypes = consRepository.FindAllMeasurements(); 
    ViewData["MeasurementType"] = mesurementTypes; 
    return View(); 
} 

或:

public ActionResult Create() 
{ 
    ViewData["MeasurementType"] = new SelectList(db.MeasurementTypes, "Id", "Name"); 
    return View(); 
} 

还有使用强类型视图中的第三和首选方式:

public ActionResult Create() 
{ 
    var measurementTypes = new SelectList(db.MeasurementTypes, "Id", "Name"); 
    return View(measurementTypes); 
} 

,并在视图:

<%= Html.DropDownList("MeasurementType", Model, "-- Select Value ---") %> 
+0

@Ya darin that worked ...如何将“选择”添加为该列表中的第0个索引? – 2010-05-03 06:23:48

+0

+1 Darin :) arg,我太慢了:( – 2010-05-03 06:25:32

+0

@PieterG如何在该列表中添加“Select”作为第0个索引? – 2010-05-03 06:26:19

1

如错误消息所示,您需要IEnumerable<SelectList>而不是IEnumerable<Materials>

SelectList的构造函数有一个需要IEnumerable的重载。见.net MVC, SelectLists, and LINQ

+0

@Robert看看我的编辑... – 2010-05-03 06:17:44

+0

@Pandiya:恩,这是一个完全不同的问题。我看到你找到了'SelectList'。 – 2010-05-03 14:11:02