ɐsɹǝʌ ǝɔıʌ
ɐsɹǝʌ ǝɔıʌ

Reputation: 4512

Populating dropdown list with two columns from database

I'm working on MVC3 project.

At my controller I already have a code that gets the Descr column from StockClass table. After that I fill a ViewBag with this list in order to retrieve it from the view and populate the dropdown list.

Currently is working fine but only shows Descr field (obviously). What i want is populate the dropdown list with two fields (Code and Descr) in this format: "code - descr".

I tried several ways but i cannot find the way to code the @Html helper correctly.

In my controller...

var oc = dba.StockClass.OrderBy(q => q.Code).ToList();
ViewBag.OrderClass = new SelectList(oc, "StockClassId", "Descr");

In my view....

@Html.DropDownList("StockClassID", (SelectList)ViewBag.OrderClass)

Could you please help me?

Upvotes: 0

Views: 845

Answers (1)

Steve Wilkes
Steve Wilkes

Reputation: 7135

I don't believe there is an HTML Helper which will do that for you, but you can get what you're after like this:

var oc = dba.StockClass
    .OrderBy(q => q.Code)
    .ToDictionary(q => q.StockClassId, q => q.Code + " - " + q.Descr);

ViewBag.OrderClass = new SelectList(oc, "Key", "Value");

This also has the advantage of making the uses of StockClassId, Code and Descr refactor-friendly - if you rename those properties you won't be able to compile without updating this bit of code to match.

Upvotes: 3

Related Questions