Combine 2 fields in SelectList
Asked Answered
F

1

5

Currently I have SelectList that writes ID, and shows FirstName on the form.

ViewBag.Person = new SelectList(db.Person, "ID", "FirstName");

How to concatenate FirstName and LastName into SelectList? Something like:

ViewBag.Person = new SelectList(db.Person, "ID", "FirstName & LastName");
Fourposter answered 4/2, 2013 at 12:44 Comment(1)
Possible DuplicateCrenel
G
8

Try something like this:

ViewBag.Person = 
new SelectList((from s in db.Person select new { 
    ID=s.ID,
    FullName = s.FirstName+ " " + s.LastName}), 
    "ID", 
    "FullName", 
    null);

Or Add a new property to your Person model

public string Fullname 
{
    get 
    {
        return string.Format("{0} {1}", FirstName, LastName);
    }
}
Gastrectomy answered 4/2, 2013 at 12:50 Comment(1)
Very nice solution. I would definitely recommend adding it to the model as shown in the second example above. This way you can reuse the "Fullname" property from other parts of your application.Inly

© 2022 - 2024 — McMap. All rights reserved.