String Formatting for SelectList

420 views Asked by At

If I have a database table that looks like this:

| ID |    FirstName    |    LastName    |
_________________________________________

   1         John              Doe
   2         Test             Subject

And I want to create a dropdownlist of full names, how would I go about doing so?

var fullNameSelectList = new SelectList(db.Test, "ID", "FirstName"); // Gives me a ddl of only firstnames

var fullNameSelectList = new SelectList(db.Test, "ID", "FirstName" + "LastName"); // Gives me error, database doesn't contain property with name FirstNameLastName

Is there a way to combine those properties within the SelectList overload?

I know I can create a ViewModel, but I just want to know if this is possible first.

Any help is appreciated.

1

There are 1 answers

2
tym32167 On BEST ANSWER

You can try this

var fullNameSelectList = new SelectList(
     db.Test.Select(x => new {x.ID, FullName = x.FirstName + " " + x.LastName}).ToArray(), 
    "ID", "FullName");