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. IP工具类-自己动手做个ip解析器

    IP工具类-自己动手做个ip解析器 一.资料准备 导入依赖包:

  2. ubuntu16.04下opencv安装笔记和例程

    问题: 最近重装了系统,需要重新配置opencv2.4.13,配置完成后每次都出现cmake error,google了报错,尝试了各种方法,都未解决问题,于是重新git clone 了opencv2 ...

  3. Linked List Cycle

    Given a linked list, determine if it has a cycle in it. /** * Definition for singly-linked list. * s ...

  4. 双向广搜 codevs 3060 抓住那头奶牛

    codevs 3060 抓住那头奶牛 USACO  时间限制: 1 s  空间限制: 16000 KB  题目等级 : 黄金 Gold   题目描述 Description 农夫约翰被告知一头逃跑奶牛 ...

  5. 平摊分析 Amortized Analysis ------geeksforgeeks翻译

    当偶尔一切操作很花的时间很慢,而大多数操作的时间都很快的时候,平摊分析的方法就很很好用了.在平摊分析中,我们分析一串操作并且可以得到最坏情况下的平均时间复杂度.例如hash table, disjoi ...

  6. mac os利用xampp实现apache下的cgi

    折腾了两天终于把问题解决了,mac os是10.10.3..够新了吧 系统原生的apache配置cgi老是配不好,突然发现xampp也有macos版的,准备下下来试试. 安装完成后,打开apache服 ...

  7. 2014 Super Training #6 B Launching the Spacecraft --差分约束

    原题:ZOJ 3668 http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=3668 典型差分约束题. 将sum[0] ~ sum ...

  8. HDU 3400 Line belt【三分套三分】

    从A出发到D,必定有从AB某个点E出发,从某个点F进入CD 故有E,F两个不确定的值. 在AB上行走的时间   f = AE / p 在其他区域行走的时间 g = EF / r 在CD上行走的时间   ...

  9. Unity 物理引擎动力学关节

    Unity物理引擎中的各个动力学关节 Hinge Joint (铰链关节) Fixed Joint (固定关节) Spring Joint (弹簧关节) Character Joint(角色关节) C ...

  10. git rebase 介绍

    git rebase是对commit history的改写.当你要改写的commit history还没有被提交到远程repo的时候,也就是说,还没有与他人共享之前,commit history是你私 ...