user2029541
user2029541

Reputation: 666

MVC orderby on dropdownlist

I have a dropdown list that is set in a table. I originally let the unique ID of the table be the control for the order of the list of items. However work have requested a change of this order. I could rearrange the table to it still orders using the unique Identifier but I believe this order will change regularly until they are happy. so I have added a field called zoneOrder. The trouble I am having is how to order by using the below code

ViewBag.zoneId = new SelectList(db.tblZoneLists, "zoneId", "zoneDesc");

I have tried

ViewBag.zoneId = new SelectList(db.tblZoneLists, "zoneId", "zoneDesc").OrderByDescending(e=>e.zoneOrder)

but this doesn't work, in fact when I type the e=>e. the intellisense only gives me options such a 'value', 'text'

Upvotes: 4

Views: 6688

Answers (1)

Andrei V
Andrei V

Reputation: 7496

You need to reorder that a bit:

ViewBag.zoneId = new SelectList(db.tblZoneLists
                                  .OrderByDescending(e=>e.zoneOrder), 
                 "zoneId", "zoneDesc")

The SelectList object is a list of SelectListItems. Each SelectListItem has 3 properties: Text, Value and Selected. When you call OrderByDescending on the SelectList, you are actually trying to order a list of SelectListItems. That's why Intellisense is suggesting the Value property.

Since you are trying to order your DropDownList, you should first order the data source, i.e. tblZoneLists. That's why you fist order the data and then pass it to the SelectList constructor.

Upvotes: 7

Related Questions