user1662812
user1662812

Reputation: 2601

How to sort all dropdownLists by name in ASP.net MVC

Is it possible to automatically sort all dropdownLists in ASP.net MVC project?

I don't want to go one by one and sort them explicitly. Is there a way to do this automatically on all dropdownLists in the project?

Upvotes: 0

Views: 147

Answers (2)

Miloš Ostojić
Miloš Ostojić

Reputation: 132

You could create HtmlHelperExtension class as friism sugested, or you could create extension method on SelectList like this:

public static class SortedList
{
        public static void SortList(this SelectList selectList, SortDirection direction)
        {
            //sort content of selectList
        }
}

and then use it like this:

var sel = new SelectList(new List<string> {"john", "mary", "peter"});
sel.SortList(SortDirection.Ascending);

Either way, you are going to change every line of code where you want to sort those lists.

Upvotes: 0

friism
friism

Reputation: 19279

Create a HtmlHelperExtensions class that has an extension method that does what you want. Something like this:

public static class HtmlHelperExtensions
{
    public static MvcHtmlString SortedDropDownList(this HtmlHelper htmlHelper, string name, IEnumerable<SelectListItem> selectList)
    {
        return htmlHelper.DropDownList(name, selectList.OrderBy(x => x.Text));
    }
}

Whatever namespace you stick the helper in, make sure it's added to configuration\system.web.webPages.razor\pages\namespaces in the web.config found in your \Views folder so that you can use it in your view.

Upvotes: 1

Related Questions