Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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'

like image 474
user2029541 Avatar asked Mar 18 '23 12:03

user2029541


1 Answers

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.

like image 127
Andrei V Avatar answered Mar 24 '23 08:03

Andrei V