本文转自:
The first and most important part of your code would be to get rid of any ViewBag/ViewData (which I personally consider as cancer for MVC applications) and use view models and strongly typed views. So let's start by defining a view model which would represent the data our view will be working with (a dropdownlistg in this example):public class MyViewModel{ public string SelectedItem { get; set; } public IEnumerableItems { get; set; }}then we could have a controller:public class HomeController : Controller{ public ActionResult Index() { var model = new MyViewModel { // I am explicitly putting some items out of order Items = new[] { new SelectListItem { Value = "5", Text = "Item 5" }, new SelectListItem { Value = "1", Text = "Item 1" }, new SelectListItem { Value = "3", Text = "Item 3" }, new SelectListItem { Value = "4", Text = "Item 4" }, } }; return View(model); }}and a view:@model MyViewModel@Html.DropDownListForSorted( x => x.SelectedItem, Model.Items, new { @class = "foo" })and finally the last piece is the helper method which will sort the dropdown by value (you could adapt it to sort by text):public static class HtmlExtensions{ public static IHtmlString DropDownListForSorted ( this HtmlHelper helper, Expression > expression, IEnumerable items, object htmlAttributes ) { var model = helper.ViewData.Model; var orderedItems = items.OrderBy(x => x.Value); return helper.DropDownListFor( expression, new SelectList(orderedItems, "Value", "Text"), htmlAttributes ); }}