2014-10-19 48 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"); 

但为什么我必须这样做呢?在我看来,最初的代码应该已经工作。