开发者

How to populate a DropDownList in ASP.Net MVC2?

I have the following database schema:

How to populate a DropDownList in ASP.Net MVC2?

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:

How to populate a DropDownList in ASP.Net MVC2?


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 ;)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜