• [转]Best way to sort a DropDownList in MVC3 / Razor using helper method


    本文转自:http://stackoverflow.com/questions/7223185/best-way-to-sort-a-dropdownlist-in-mvc3-razor-using-helper-method

    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 IEnumerable<SelectListItem> Items { 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<TModel, TProperty>(
            this HtmlHelper<TModel> helper, 
            Expression<Func<TModel, TProperty>> expression, 
            IEnumerable<SelectListItem> 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
            );
        }
    }
  • 相关阅读:
    Docker 安装及使用
    明明白白学 同步、异步、阻塞与非阻塞
    ArrayList 并发操作 ConcurrentModificationException 异常
    shell 脚本防止ddos
    shell 脚本备份数据库
    shell 脚本猜数字
    shell 脚本检测主从状态
    tomcat 结合apache 动静分离
    shell 脚本检测网站存活
    zabbix 4.0 版本 yum安装
  • 原文地址:https://www.cnblogs.com/freeliver54/p/3170958.html
Copyright © 2020-2023  润新知