MVC4: How to sort this selectlist/dropdownlist

user2423801 picture user2423801 · May 27, 2013 · Viewed 10.7k times · Source

I'm working with MVC4.

I have this 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 the "Name". What should I do?

Many thanks! :)

Answer

AliRıza Adıyahşi picture AliRıza Adıyahşi · May 27, 2013

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);