MVC4: how to sort this list / drop down list

I work with MVC4.

I have the following dropdownlist / selectlist:

@Html.DropDownList("EmployerID", String.Empty) ViewBag.EmployerID = new SelectList(db.Employers, "EmployerID", "Name", contact.EmployerID); 

and I want this dropdownlist / selectlist to be sorted by "Name". What should I do?

Thank you very much!:)

+4
source share
2 answers

Add OrderBy to your db.Employers

 @Html.DropDownList("EmployerID", String.Empty) ViewBag.EmployerID = new SelectList(db.Employers.OrderBy(x => x.Name), "EmployerID", "Name", contact.EmployerID); 
+7
source

I thought I would share this solution that I came across if others would have the same problem as mine. Im works with generics, and therefore I can not order my source before creating SelectList. However, you can order the created SelectList. I still wanted my method to return SelectList, so I call SelectList () a second time using an ordered SelectList as a source. :)

 var orderedSelectList = new SelectList(source, "YourValueFieldName", "YourTextFieldName", selectedCode).OrderBy(i => i.Text); return new SelectList(orderedSelectList, "Value", "Text", selectedCode); 
+3
source

Source: https://habr.com/ru/post/1482886/


All Articles