2014-10-19 94 views
0

這段代碼讓我感到困惑,看起來像我缺少一些東西。SelectList未使用ViewBag填充

型號

public class County 
{ 
    public int ID { get; set; } 
    public string Name { get; set; } 
} 

public class Education 
{ 
    public int ID { get; set; } 
    public string Title { get; set; } 
} 

控制器

public ActionResult Create() 
{ 
    ViewBag.ListOfCounties = new SelectList(db.Counties, "ID", "Name"); 
    ViewBag.ListOfEducations = new SelectList(db.Educations, "ID", "Title"); 

    return View(); 
} 

查看

@Html.DropDownListFor(model => model.Person.County, ViewBag.ListOfCounties as SelectList, "Choose county") 
@Html.DropDownListFor(model => model.Person.Education, ViewBag.ListOfEducations as SelectList, "Choose education") 

縣名單是rendere通常情況下,但教育名單是空白的。 區別在於我在「教育」中使用「標題」而不是「名稱」。

然後我嘗試在我的模型和控制器中將「標題」重命名爲「名稱」,然後列表正常顯示。

但我想用「標題」而不是「名稱」!

回答

0

我找到了一個解決方案,在我的控制器中,我改變了它。

ViewBag.ListOfEducations = new SelectList(db.Educations.Select(c => new { c.ID, c.Title }), "ID", "Title"); 

但爲什麼我必須這樣做呢?在我看來,最初的代碼應該已經工作。