Michael
Michael

Reputation: 173

ASP.NET MVC 3 - @Html.DropDownList - How do I change the description?

The following code in a cshtml file creates a dropdown with a list of Contacts, but the field it uses for the description of values, is not the one I want to display.

How do I force it to choose data from a different field in the Contact object?

    @Html.DropDownList("ContactId", String.Empty)

Upvotes: 2

Views: 1033

Answers (2)

Cacho Santa
Cacho Santa

Reputation: 6914

You can try something like this on the server side(controller):

ViewBag.ContactList = new SelectList(iContactRepository.GetAllContacts(),
                                     "ContactId", "Name", contactDefault.ContactId);

//Here the method GetAllContacts returns Iqueryable<Contact>.

And this on the view:

@Html.DropDownList("ContactIdSelect", ViewBag.ContactList as SelectList)

This is the SelectList documentation.

Hope it helps.

Upvotes: 1

jim tollan
jim tollan

Reputation: 22485

@Html.DropDownListFor(a => a.OtherContactId, 
    new SelectList(Model.ContactList, "ContactId", "ContactValue", 
        Model.OtherContactId), "-- Select --")

where, Model.ContactList is populated in your controller action.

p.s. I'm not entirely certain whether you mean change the title of the select option text or the property that is updated, so have presented a kind of hybrid offering

Upvotes: 1

Related Questions