Asp.net mvc 2 如何在ASP.NETMVC2中填充DropDownList?

Asp.net mvc 2 如何在ASP.NETMVC2中填充DropDownList?,asp.net-mvc-2,drop-down-menu,Asp.net Mvc 2,Drop Down Menu,我有以下数据库架构: 以下是我如何在AreaController.cs中填充DropDownList: public ActionResult Edit(int id) { Area area = areaRepository.GetArea(id); JefeRepository jefe = new JefeRepository(); ViewData["Jefes"] = new SelectList(jefe.FindAllJefes().ToList(), "

我有以下数据库架构:

以下是我如何在AreaController.cs中填充DropDownList:

public ActionResult Edit(int id)
{
    Area area = areaRepository.GetArea(id);
    JefeRepository jefe = new JefeRepository();
    ViewData["Jefes"] = new SelectList(jefe.FindAllJefes().ToList(), "ID", "Nombre", area.Jefe.Nombre);
    return View(area);
}
在我看来,我是这样显示的:

<%: Html.DropDownList("IDJefe", (SelectList)ViewData["Jefes"]) %>  
这就是它的表现:

在您的类中,您可以创建一个属性,该属性将为您组合该属性,也可以绑定到您的列表,例如,如果我有Person类:

public class Person
{
   public int Id { get; set; }
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public string FullName { get { return string.Format("{0} {1}", FirstName, LastName); } }
}
然后您可以轻松地将其绑定为:

ViewData["Persons"] = new SelectList(persons, "Id", "FullName ", ...);
只要它有一个getter,它就不会涉及到您的业务逻辑流程中——它只会有帮助;)


抱歉再举一个例子,但我真的不懂西班牙语;)

我试着输入“Nombre”+“Apellido”,它给了我一个异常,说明模型没有那个属性。我试试你的建议只能指定一个将绑定为显示成员的公共成员。将两者结合在一起的属性将完成此任务:)请尝试我的示例,并告诉我它是否解决了您的问题…工作非常完美。回答得很好!:)我将为这个常见问题编写一个教程。再次感谢。
ViewData["Persons"] = new SelectList(persons, "Id", "FullName ", ...);