2010-05-03 76 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