博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
[转]Best way to sort a DropDownList in MVC3 / Razor using helper method
阅读量:5736 次
发布时间:2019-06-18

本文共 1758 字,大约阅读时间需要 5 分钟。

本文转自:

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
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
( 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 ); }}

 

 

转载地址:http://glrwx.baihongyu.com/

你可能感兴趣的文章
AWS推出深度学习容器,简化AI程序开发
查看>>
算法(第4版) Chapter 1
查看>>
前端技术选型的遗憾和经验教训
查看>>
“亲切照料”下的领域驱动设计
查看>>
GIT
查看>>
微软宣布公开预览其内容分发网络
查看>>
SRE工程师到底是做什么的?
查看>>
解读:Red Hat为什么收购Ansible
查看>>
spring整合mybatis是如何配置事务的?
查看>>
Educational Codeforces Round 21(A.暴力,B.前缀和,C.贪心)
查看>>
Mina2.0框架源码剖析(七)
查看>>
LIST<T>现在也支持序列化和反序列化了
查看>>
【转】Android世界的Swift - Kotlin语言
查看>>
基于Spring Boot的Logback日志轮转配置
查看>>
3.2. Access Privilege System
查看>>
基于Metronic的Bootstrap开发框架经验总结(18)-- 在代码生成工具Database2Sharp中集成对Bootstrap-table插件的分页及排序支持...
查看>>
用原型继承方法
查看>>
JPG、PNG和GIF图片的基本原理及优…
查看>>
linux内存条排查
查看>>
解决cacti监控windows网卡带有中文
查看>>