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.
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.
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 -") %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With