2014-08-28 72 views
1

我在用的這個數據填充一個下拉列表:ASP.NET獲得值的DropDownList

 return _lamb_database.Lambs().Select(lamb => new SelectListItem 
     { 
      Text = lamb.LambName, 
      Value = lamb.LambID.ToString() 
     }).ToList(); 

我然後使用視圖模型通過這個列表的視圖。在視圖我顯示在視圖模型中的項目使用此代碼:

 @Html.DropDownListFor(m => m.SelectedLamb, Model.Facilities, "Select Lamb") 

SelectedLamb是一個整數,給出了在數據庫中的羊肉獨特的IDENTIFER。我想回傳羊肉的唯一標識符而不是羊肉的名字。你可以在上面看到,我試圖讓這個列表設置SelectedLamb。

我收到此錯誤:

The ViewData item that has the key 'SelectedLamb' is of type 'System.Int32' but must be of type 'IEnumerable'.

有誰知道我能得到這個工作?現在我已經花了這麼長時間了。

+0

是'Model.Facilities' typeof'SelectList'? – 2014-08-28 09:26:10

+0

它是IEnumerable類型的 user3412625 2014-08-28 09:35:03

+0

你確定你已經初始化它嗎? ('MyModel.Facilities = theFuntionAbove;') - 如果該屬性爲null或模型爲null,則可能發生此消息 – 2014-08-28 09:36:24

回答

1

提交後需要重新設置Facilities屬性。

[HttpPost] 
public ActionResult YourActionName(YourModel model) 
{ 
    model.Facilities = ..; // set again 
    return View(model); 
} 
+1

非常感謝,這工作! – user3412625 2014-08-28 09:43:19