Enum扩展及MVC中DropDownListFor扩展方法的使用

时间:2021-12-08 22:14:04
        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

Enum扩展及MVC中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