How to populate a DropDownList in ASP.Net MVC2?
I have the following database schema:
Here's how I populate a DropDownList in my AreaController.cs:
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);
}
Then in my View I display it like so:
<%: Html.DropDownList("IDJefe", (SelectList)ViewData["Jefes"]) %>
The DropDownList loads correctly but only shows the Name of the Jefe. I want to display both name and last name. How can I achieve t开发者_运维知识库his?
I've tried doing something like this but it only display the first name.
ViewData["Jefes"] = new SelectList(jefe.FindAllJefes().ToList(), "ID", "Nombre", area.Jefe.Nombre + area.Jefe.Apellido);
This is how it shows:
In your class you can make an property which will combine it for you and also can be bind to your list, f.e. if I have Person class:
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); } }
}
Then you can easily bind it like:
ViewData["Persons"] = new SelectList(persons, "Id", "FullName ", ...);
As far as it have just the getter it will not involved into your business logic processes - it will only helps ;)
PS. Sorry for another example, but I really do not understand spanish ;)
精彩评论