Scanner
Scanner

Reputation: 617

How do I reorder my dropdown list in MVC 5?

I have a dropdown list in my MVC 5 application, which is a rating scale from 1 to 10, however 10 is just below 1 instead of being at the end of the list. So that the list runs 1, 10, 2, 3 etc. Is there a way of rectifying this? My list isn't hardcoded, it's being populated from a database.

Below is my MVC code for the dropdown list:

@Html.LabelFor(model => model.Rating, "Rating", new { @class = "control-label col-md-4" })

@Html.DropDownList("Rating", String.Empty)
@Html.ValidationMessageFor(model => model.Rating)

Upvotes: 0

Views: 711

Answers (1)

Vsevolod Goloviznin
Vsevolod Goloviznin

Reputation: 12324

Just sort them before converting to drop-down list.

var values = db.Rating.OrderByDescending(o => o.Rate).ToList(); 
var dropdownlist = values.Select(s => new SelectListItem{Value = s.Rate.ToString(), Name = s.Name}).ToList(); 
ViewBag.List = dropdownlist;

//in your view
Html.DropwDownList("Rating", (List<SelectListItem>)ViewBag.List);

If your rating is stored as a string, then you should cast it to int before ordering. Try this:

var values = db.Rating.Select(s => new {Rate = Convert.ToInt32(s.Rate}, Id = s.Id).OrderByDescending(o => o.Rate).ToList();

Upvotes: 3

Related Questions