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?
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?
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.
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.