2010-09-02 55 views
3

好日子,問題與MVC2 DropDownListFor,只顯示類名

我有Html.DropDownListFor這個問題我似乎不能,如果上班了..它給我的選擇正確的號碼,我在它應該呈現列表中的代碼中設置斷點,在「SelectItemList」對象包含正確的值的項目,但它吐出來的是實際的HTML如下:

<select id="Reason_ReasonId" name="Reason.ReasonId"><option>System.Web.Mvc.SelectListItem</option> 
<option>System.Web.Mvc.SelectListItem</option> 
<option>System.Web.Mvc.SelectListItem</option> 
<option>System.Web.Mvc.SelectListItem</option> 
<option>System.Web.Mvc.SelectListItem</option> 
<option>System.Web.Mvc.SelectListItem</option> 
</select> 

模塊containts這:

public SelectList ReasonList 
{ 
    get 
    { 
     SelectList selectList; 
     List<SelectListItem> selectItems; 

     using (var db = new EscalationDataContext()) 
     { 
      var reasons = 
       db.Reasons 
       .OrderBy(r => r.Reason1) 
       .Select(r => new SelectListItem 
       { 
        Value = r.ReasonId.ToString(), 
        Text = r.Reason1 
       }); 

      selectItems = reasons.ToList(); 

      selectList = new SelectList(selectItems); 
     } 

     return selectList; 
    } 
} 

控制器只需創建一個默認實例,並設置默認值:

public ActionResult Create() 
    { 
     EscalationModel model = new EscalationModel 
     { 
      Reason = new Reason { ReasonId = new Guid("598c28c2-877a-44fa-9834-3241c5ee9355"), Reason1 = "Taken too long" }, 
      ActionedDate = DateTime.Now 
     }; 

     return View(model); 
    } 

最後但並非最不重要的,認爲:

<%: Html.DropDownListFor(m => m.Reason.ReasonId, Model.ReasonList) %> 

任何想法,爲什麼它的行爲這樣的嗎?正如我所說,在實際的代碼(在視圖中)我有正確的值,但..它不喜歡我..任何幫助將不勝感激,在此先感謝!

回答

6

確定..看來你必須指定使用哪個變量在SelectListItem的 「價值」 和用於 「文本」 ..

selectList = new SelectList(selectItems); 

成了..

selectList = new SelectList(selectItems, "Value", "Text"); 

這似乎已經成功了!

+0

這幫了我,謝謝。 – 2012-11-16 10:45:28