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. 文件输入流 FileInputStream类 文件输出流FileOutputStream ---转载

    转载自---http://blog.csdn.net/hguisu/article/details/7418161 111:文件输入流: FileInputStream可以使用read()方法一次读入 ...

  2. ES5严格模式(Strict mode)

    严格模式(Strict mode)是由ECMA-262规范定义的新兴JavaScript标准,第五版发布于2009年12月.旨在改善错误检查功能并且标识可能不会延续到未来JavaScript版本的脚本 ...

  3. [分享]一个String工具类,也许你的项目中会用得到

    每次做项目都会遇到字符串的处理,每次都会去写一个StringUtil,完成一些功能. 但其实每次要的功能都差不多: 1.判断类(包括NULL和空串.是否是空白字符串等) 2.默认值 3.去空白(tri ...

  4. 获取bing每日图片

    http://global.bing.com/HPImageArchive.aspx?format=xml&idx=0&n=1&mkt=en-US 其中idx表示倒数第几张图片 ...

  5. malloc calloc 和 realloc

    realloc()函数 原型:extern void *realloc(void *mem_address, unsigned int newsize); 语法:指针名=(数据类型*)realloc( ...

  6. c# App.Config详解

    c# App.Config详解 应用程序配置文件是标准的 XML 文件,XML 标记和属性是区分大小写的.它是可以按需要更改的,开发人员可以使用配置文件来更改设置,而不必重编译应用程序. 配置文件的根 ...

  7. hadooop2.6 job pending research

    https://hadoop.apache.org/docs/r2.6.0/hadoop-project-dist/hadoop-common/ClusterSetup.html 我使用的是已经运行在 ...

  8. shell script 学习笔记-----标准输出

    1.将标准输出(stdout)和标准错误输出(stderr)分别重定向到两个不同的文件 其中符号'>'默认将标准输出重定向,意思和'1>'相同,‘2>'表示重定向标准错误输出,数字1 ...

  9. JAVA NIO概述(一):I/O模型

    NIO是jdk1.4加入的新功能,我们一般成为非阻塞IO,在1.4之前,JAVA中的都是BIO(堵塞IO),BIO有以下几个缺点: 没有数据缓冲区,I/O性能存在问题 没有C/C++中channel( ...

  10. C# WinForm 中Console 重定向输出到ListBox控件中显示

                        {              VoidAction action =              {                  lstBox.Items. ...