Enum扩展及MVC中DropDownListFor扩展方法的使用
public enum SearchState
{
/// <summary>
/// 全部
/// </summary>
[Description("全部")]
NoChoose=-,
/// <summary>
/// 待审核
/// </summary>
[Description("待审核")]
NotAudit = ,
/// <summary>
/// 已审核
/// </summary>
[Description("已审核")]
PassAudit = ,
/// <summary>
/// 驳回
/// </summary>
[Description("拒绝")]
NoAudit = , } public static class EnumExt
{
public static string GetDescription(this Enum sourceEnum)
{
object enumValue = (object)sourceEnum;
Type enumType = sourceEnum.GetType();
return enumType.GetEnumDescription(enumValue);
} //获取Enum枚举值@(typeof(AppEnum.SearchState).GetEnumDescription(item.State))
public static string GetEnumDescription(this Type enumType, object enumValue)
{
try
{
FieldInfo fi = enumType.GetField(Enum.GetName(enumType, enumValue));
var attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);
return (attributes.Length > ) ? attributes[].Description : Enum.GetName(enumType, enumValue);
}
catch
{
return "UNKNOWN";
}
} public static string GetEnumName(this Type enumType, object enumValue)
{
try
{
return Enum.GetName(enumType, enumValue);
}
catch
{
return "UNKNOWN";
}
} //获取list;@Html.DropDownListFor(m => m.SearchManCheckDetail.AuditState, new KvSelectList(typeof (AppEnum.SearchState).GetEnumList())) public static SortedList<int, string> GetEnumList(this Type enumType)
{
SortedList<int, string> sortedList = null;
var enumNames = Enum.GetValues(enumType);
int length = enumNames.Length;
if (length > )
{
sortedList = new SortedList<int, string>();
for (int i = ; i < length; i++)
{
string enumName = enumNames.GetValue(i).ToString();
object enumValue = Enum.Parse(enumType, enumName);
string enumDescription = enumType.GetEnumDescription(enumValue);
sortedList.Add((int)enumValue, enumDescription);
}
}
return sortedList;
} public static SortedList<string, string> GetEnumStringList(this Type enumType)
{
SortedList<string, string> sortedList = null;
var enumNames = Enum.GetValues(enumType);
int length = enumNames.Length;
if (length > )
{
sortedList = new SortedList<string, string>();
for (int i = ; i < length; i++)
{
string enumName = enumNames.GetValue(i).ToString();
object enumValue = Enum.Parse(enumType, enumName);
string enumDescription = enumType.GetEnumDescription(enumValue);
sortedList.Add(enumName, enumDescription);
}
}
return sortedList;
}
}
string meijuname=Enum.GetName(typeof(ProductStateEnum),checkStateValue);
var reluser = typeof(StoredTypeEnum).GetEnumStringList().Where(ty => ty.Key == t.StoredType);
freq.IsCardTypeOrder = EnumExtensions.GetDescription((CardtypeEnum)Convert.ToInt32(t.CardType));
一、非强类型:
//Controller:
ViewData["AreId"] = from a in rp.GetArea()
select new SelectListItem {
Text=a.AreaName,
Value=a.AreaId.ToString()
};
//View:
@Html.DropDownList("AreId")
还可以给其加上一个默认选项:@Html.DropDownList("AreId", "请选择");
二、强类型:
DropDownListFor常用的是两个参数的重载,第一参数是生成的select的名称,第二个参数是数据,用于将绑定数据源至DropDownListFor

下面对方法进行扩展:
public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, bool isHasAll)
{
//return DropDownListFor(htmlHelper, expression, selectList, null /* optionLabel */, null /* htmlAttributes */);
MvcHtmlString mvcHtmlString = htmlHelper.DropDownListFor(expression, selectList);
//无可选项时直接返回
if (selectList.Count() <= )
{
return mvcHtmlString;
}
if (!isHasAll)
{
return mvcHtmlString;
}
string htmlString = mvcHtmlString.ToHtmlString(); const string entryFlag = "<option";
int index = htmlString.IndexOf(entryFlag, System.StringComparison.Ordinal); const string appendHtml = "<option value=''>--ALL--</option>";
string result = htmlString.Insert(index, appendHtml); return new MvcHtmlString(result);
} //控制DropDownList为禁用
public static MvcHtmlString DropDownListDisabledFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList)
{
return htmlHelper.DropDownListFor(expression, selectList, new { disabled = "disabled" });
}
@{
var list = new Dictionary<int, string>();
list.Add(, "全部");
list.Add(, "关键字");
list.Add(, "分类id");
list.Add(, "品牌id");
}
@Html.DropDownListFor(m => m.Products.KeyWordType, new KvSelectList(list))
//Enums.IsEnable.True为默认值;最后参数false为不显示全部默认选项
@Html.DropDownListFor(m => m.IsEnable, new KvSelectList(typeof(Enums.IsEnable).GetEnumStringList(), Enums.IsEnable.True), false)
//最后参数true为显示全部或请选择的那个默认选项
@Html.DropDownListFor(m => m.Details.IsTop, new KvSelectList(typeof(Enums.IsTop).GetEnumList()), true)
KvSelectList 实体集合类:
public class KvSelectList : SelectList
{
public KvSelectList(IEnumerable items)
: base(items, "Key", "Value")
{
} public KvSelectList(IEnumerable items, object selectedValue)
: base(items, "Key", "Value", selectedValue)
{
} public KvSelectList(IEnumerable items, string dataValueField, string dataTextField)
: base(items, dataValueField, dataTextField)
{
} public KvSelectList(IEnumerable items, string dataValueField, string dataTextField, object selectedValue)
: base(items, dataValueField, dataTextField, selectedValue)
{
}
}
引申:应用非匿名类及字典的方式都可以实现对htmlAttributes的动态控制
@Html.DropDownListFor(m => m.ClassID, ViewBag.List as SelectList, new { @style = "width:280px;", size = "", disabled = "disabled" })
对于这个htmlAttributes,它可接受的数据类型可以是一个Object或IDictionary(string,Object),而我们在DropDownListFor扩展方法中所写的new { @style = "width:280px;"}其实是一个匿名类。
通过非匿名类的方式动态控制htmlAttributes
var attList = new { @style = "width:280px;", size = "" };
@Html.DropDownListFor(m => m.ClassID, ViewBag.List as SelectList, attList)
但是当我们试图去更改属性值的时候,VS会提示无法对属性赋值,这是因为这个匿名类的相关属性只有get属性,没有set属性。
接下来,我们通过建立一个非匿名类来实现htmlAttributes的动态调用。
建立一个cs文件,然后在这个cs文件中新建一个htmlAttributes属性类,代码如下:
public class AttClass
{
public string style { get; set; }
public string size { get; set; }
}
然后在VIEW中实例化这个类并为其属性赋值:
AttClass att = new AttClass();
att.size = "";
att.style = "width:800px";
完成后就可以在DropDownListFor中使用这个实例化的对象了
@Html.DropDownListFor(m => m.ClassID, ViewBag.List as SelectList, att)
通过IDictionary字典实现动态控制htmlAttributes属性
IDictionary<string, object> att = new Dictionary<string, object>();
att.Add("size","");
att.Add("style", "width:280px;");
@Html.DropDownListFor(m => m.ClassID, ViewBag.List as SelectList, att)
关于动态控制routeValues的方法
比如我们调用一个Url.Action方法,其中的routeValues不能直接使用上面的IDictionary来实现,但可以使用RouteValueDictionary来实现。
@{
RouteValueDictionary att = new RouteValueDictionary();
att.Add("tbPre", "Module");
att.Add("FirstText", "作为一级分类");
if (!string.IsNullOrEmpty(Html.ViewContext.RouteData.Values["id"].ToString()))
{
att.Add("SelectedValue", Html.ViewContext.RouteData.Values["id"]);
}
}
@Html.Action("index", "ClassList", att)
另外,RouteValueDictionary的构造函数也提供了在初始化RouteValueDictionary对象的时候将IDictionary复制元素到RouteValueDictionary中的方法。
参考博客:http://www.cnblogs.com/superfeeling/p/4898002.html
Enum扩展及MVC中DropDownListFor扩展方法的使用的更多相关文章
- MVC中的扩展点(六)ActionResult
ActionResult是控制器方法执行后返回的结果类型,控制器方法可以返回一个直接或间接从ActionResult抽象类继承的类型,如果返回的是非ActionResult类型,控制器将会将结果转换为 ...
- Asp.Net MVC中DropDownListFor的用法(转)
2016.03.04 扩展:如果 view中传入的是List<T>类型 怎么使用 DropList 既然是List<T> 那么我转化成 T List<T>的第一个 ...
- Asp.Net MVC中DropDownListFor的用法
在Asp.Net MVC中可以用DropDownListFor的方式来让用户选择已定列表中的一个数值.用法不复杂,这里简单做一个记录. 首先我们要定义一个 Model ,用户在 DropDownLis ...
- 转:Asp.Net MVC中DropDownListFor的用法
在Asp.Net MVC中可以用DropDownListFor的方式来让用户选择已定列表中的一个数值.用法不复杂,这里简单做一个记录. 首先我们要定义一个 Model ,用户在 DropDownLis ...
- 关于asp.net MVC 中的TryUpdateModel方法
有比较才会有收货,有需求才会发现更多. 在传统的WebFormk开发工作中,我们常常会存在如下的代码块 //保存 protected void btnSubmit_Click(object sende ...
- ASP.NET + MVC5 入门完整教程四---MVC 中使用扩展方法
https://blog.csdn.net/qq_21419015/article/details/80433640 1.示例项目准备1)项目创建新建一个项目,命名为LanguageFeatures ...
- MVC 中使用扩展方法
扩展方法(Extension Method)是给那些不是你拥有.因而不能直接修改的类添加方法的一种方便的办法. 一.使用扩展方法 1.定义一个购物车的类-ShoppingCart using Sys ...
- MVC中DropDownListFor的使用注意事项
1.在MVC的View页面中使用DropDownListFor时当DropDownListFor是列表是通过后台ViewBag传过来时,当ViewBag中的Key与DropDownListFor一致时 ...
- MVC中下拉列表绑定方法
方法一: 前端 @Html.DropDownListFor(a=>a.acate,ViewBag.CateList as IEnumerable<SelectListItem>) 后 ...
随机推荐
- android适配器及监听点击和滚动在ListView中的使用
package com.example.demon08; import java.util.ArrayList;import java.util.HashMap;import java.util.Li ...
- 从mysql数据表中随机取出一条记录
核心查找数据表代码: ; //此处的1就是取出数据的条数 但这样取数据网上有人说效率非常差的,那么要如何改进呢 搜索Google,网上基本上都是查询max(id) * rand()来随机获取数据. S ...
- Java性能调优笔记
Java性能调优笔记 调优步骤:衡量系统现状.设定调优目标.寻找性能瓶颈.性能调优.衡量是否到达目标(如果未到达目标,需重新寻找性能瓶颈).性能调优结束. 寻找性能瓶颈 性能瓶颈的表象:资源消耗过多. ...
- ZooKeeper系列1:ZooKeeper的配置
问题导读:1.zookeeper有哪些配置文件?2.zookeeper最低配置需要哪些配置项?3.zookeeper高级配置需要配置哪些项? ZooKeeper 的功能特性通过 ZooKeeper 配 ...
- redis 一二事 - 搭建集群缓存服务器
在如今并发的环境下,对大数据量的查询采用缓存是最好不过的了,本文使用redis搭建集群 (个人喜欢redis,对memcache不感冒) redis是3.0后增加的集群功能,非常强大 集群中应该至少有 ...
- Unity使用 UnityVS+VS2013 调试脚本
好消息:UnityVS免费啦 好消息:微软收购了UnityVS公司,UnityVS免费啦 下载地址:https://visualstudiogallery.msdn.microsoft.com/sit ...
- Jenkins学习八:Jenkins语言本地化
在Jenkins中,英语一大片,不懂英语的看着头疼.非常高兴的是,Jenkins作为一个主流流行的持续构建工具,提供了一个本地化语言的配置界面. 你可以找到它,在Jenkins每页的左下角.如下图: ...
- C# 读取Excel
直接添代码: public void connExcel(string strPath) { //string strConn = @"Provider=Microsoft.Jet.OLED ...
- TestLink学习六:TestLink1.9.13工作使用小结
Testlink是一款强大的用例追踪和管理工具.测试管理注重的实际上就是一个流程. 1.默认当测试用例同名时,就会有提示.(以前版本需要修改配置) 2.测试用例序号:(缺点) 1)删除一个测试用例之后 ...
- MYSQL密码设置
当MYSQL安装成功后,root用户的密码默认是空的,有三种方式可以重新设置root账号的密码 1.用root 进入mysql后 mysql>set password =password('你的 ...