Reputation: 18859
I'm trying to display a dropdown on my view page that has a custom text value.
I'm trying to display a list a Contacts. A Contact contains a ContactID, FirstName, and LastName.
<%= Html.DropDownListFor(m => m.ContactId, new SelectList(Model.Contacts, "ContactID", "LastName"), "- Select a Contact -") %>
Right now I'm just displaying the last name, but I'd like to display the first name and last name in the dropdown.
Upvotes: 11
Views: 5578
Reputation: 371
I've been looking for the same and your question was the first result in google. I know you asked about a year ago but for all the other people that will 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 can't change the "Contact" class.
Upvotes: 27
Reputation: 31842
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 -") %>
Upvotes: 7