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扩展方法的使用的更多相关文章

  1. MVC中的扩展点(六)ActionResult

    ActionResult是控制器方法执行后返回的结果类型,控制器方法可以返回一个直接或间接从ActionResult抽象类继承的类型,如果返回的是非ActionResult类型,控制器将会将结果转换为 ...

  2. Asp.Net MVC中DropDownListFor的用法(转)

    2016.03.04 扩展:如果 view中传入的是List<T>类型 怎么使用 DropList 既然是List<T> 那么我转化成 T  List<T>的第一个 ...

  3. Asp.Net MVC中DropDownListFor的用法

    在Asp.Net MVC中可以用DropDownListFor的方式来让用户选择已定列表中的一个数值.用法不复杂,这里简单做一个记录. 首先我们要定义一个 Model ,用户在 DropDownLis ...

  4. 转:Asp.Net MVC中DropDownListFor的用法

    在Asp.Net MVC中可以用DropDownListFor的方式来让用户选择已定列表中的一个数值.用法不复杂,这里简单做一个记录. 首先我们要定义一个 Model ,用户在 DropDownLis ...

  5. 关于asp.net MVC 中的TryUpdateModel方法

    有比较才会有收货,有需求才会发现更多. 在传统的WebFormk开发工作中,我们常常会存在如下的代码块 //保存 protected void btnSubmit_Click(object sende ...

  6. ASP.NET + MVC5 入门完整教程四---MVC 中使用扩展方法

    https://blog.csdn.net/qq_21419015/article/details/80433640 1.示例项目准备1)项目创建新建一个项目,命名为LanguageFeatures ...

  7. MVC 中使用扩展方法

     扩展方法(Extension Method)是给那些不是你拥有.因而不能直接修改的类添加方法的一种方便的办法. 一.使用扩展方法 1.定义一个购物车的类-ShoppingCart using Sys ...

  8. MVC中DropDownListFor的使用注意事项

    1.在MVC的View页面中使用DropDownListFor时当DropDownListFor是列表是通过后台ViewBag传过来时,当ViewBag中的Key与DropDownListFor一致时 ...

  9. MVC中下拉列表绑定方法

    方法一: 前端 @Html.DropDownListFor(a=>a.acate,ViewBag.CateList as IEnumerable<SelectListItem>) 后 ...

随机推荐

  1. spinner下拉列表

    xml: <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:l ...

  2. nyoj 230/poj 2513 彩色棒 并查集+字典树+欧拉回路

    题目链接:http://acm.nyist.net/JudgeOnline/problem.php?pid=230 题意:给你许许多多的木棍,没条木棍两端有两种颜色,问你在将木棍相连时,接触的端点颜色 ...

  3. Hadoop,Vertica环境搭建

    本打算使用mapr的虚拟机在里面进行开发,使用eclipse进行调试,它的问题是,有时候服务不能完全起来, 如jobtracker和tasktracker,cldb没有起来,重启服务有可能解决. 但另 ...

  4. Neo4j 高可用集群安装

    安装neo4j高可用集群,抓图安装过程 http://www.ibm.com/developerworks/cn/java/j-lo-neo4j/ Step1.下载neo4j商业版并解压,复制为neo ...

  5. fiddler对手机进行抓包

    1.安装fiddler web debugger 2.Tools -->telerik fiddler options-->connections,勾选allow remote compu ...

  6. 【转】Python 列表排序

    很多时候,我们需要对List进行排序,Python提供了两个方法 对给定的List L进行排序, 方法1.用List的成员函数sort进行排序 方法2.用built-in函数sorted进行排序(从2 ...

  7. 权限框架 - shiro 自定义realm

    上篇文章中是使用的默认realm来实现的简单登录,这仅仅只是个demo,真正项目中使用肯定是需要连接数据库的 首先创建自定义realm文件,如下: 在shiro中注入自定义realm的完全限定类名: ...

  8. Studio 从入门到精通 (一)

    目标:Android Studio新手–>下载安装配置–>零基础入门–>基本使用–>调试技能–>构建项目基础–>使用AS应对常规应用开发 AS简介 经过2年时间的研 ...

  9. AndroidStudio权威教程 AS添加第三方库的6种方式(Jar module so等)

    点击项目设置按钮 依次选择 App > Dependencies 1. 直接搜索法 依次选择 + > Library dependency 这里的搜索一定要是全名的,不然搜不到哦 下图所表 ...

  10. IOS定位服务的应用

    IOS定位服务的应用 一.授权的申请与设置 二.定位服务相关方法 三.定位服务代理的相关方法 四.定位服务获取到的位置对象 五.航标定位得到的航标信息对象 IOS定位服务的应用 一.授权的申请与设置 ...