Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set custom text field in SelectList

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.

like image 576
Steven Avatar asked Feb 13 '11 05:02

Steven


2 Answers

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.

like image 107
sickbattery Avatar answered Sep 20 '22 10:09

sickbattery


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 -") %>
like image 22
LukLed Avatar answered Sep 21 '22 10:09

LukLed