Set custom text field in SelectList

I am trying to display a dropdown on my browse page with a custom text value.

I am trying to display a list of contacts. A contact contains ContactID, FirstName, and LastName.

<%= Html.DropDownListFor(m => m.ContactId, new SelectList(Model.Contacts, "ContactID", "LastName"), "- Select a Contact -") %> 

Now I just show the last name, but I would like to display the first and last name in the drop-down list.

+7
source share
2 answers

I searched the same and your question was the first result on google. I know what you asked about a year ago, but for all the other people who find this page:

  Html.DropDownListFor(m => m.ContactId, new SelectList( Model.Contacts.Select( c => new { Id = c.ContactId, FullName = c.FirstName + " " + c.LastName }), "Id", "FullName")) 

In my case, I cannot change the Contact class.

+18
source

Change your contact class, add property:

 public class Contact { public string FirstNameLastName { get { return FirstName + " " + LastName; } } } 

Then use it:

 <%= Html.DropDownListFor(m => m.ContactId, new SelectList(Model.Contacts, "ContactID", "FirstNameLastName"), "- Select a Contact -") %> 
+6
source

All Articles