0

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?

1
  • 1
    Short answer: No. Long answer: Maybe, but you would have to code an extension to the DropDownList html helper. Commented Nov 5, 2012 at 16:17

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.