Asp.net mvc MVC3枚举选择列表,使用显示注释
我有一个Html助手,可以将枚举转换为SelectList,如下所示:Asp.net mvc MVC3枚举选择列表,使用显示注释,asp.net-mvc,asp.net-mvc-3,attributes,enums,data-annotations,Asp.net Mvc,Asp.net Mvc 3,Attributes,Enums,Data Annotations,我有一个Html助手,可以将枚举转换为SelectList,如下所示: public static HtmlString EnumSelectListFor<TModel, TProperty>( this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> forExpression, object htmlAttributes, b
public static HtmlString EnumSelectListFor<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> forExpression,
object htmlAttributes,
bool blankFirstLine) where TModel : class where TProperty : struct
{
//MS, it its infinite wisdom, does not allow enums as a generic constraint, so we have to check here.
if (!typeof(TProperty).IsEnum) throw new ArgumentException("This helper method requires the specified model property to be an enum type.");
//initialize values
var metaData = ModelMetadata.FromLambdaExpression(forExpression, htmlHelper.ViewData);
var propertyName = metaData.PropertyName;
var propertyValue = htmlHelper.ViewData.Eval(propertyName).ToStringOrEmpty();
//build the select tag
var returnText = string.Format("<select id=\"{0}\" name=\"{0}\"", HttpUtility.HtmlEncode(propertyName));
if (htmlAttributes != null)
{
foreach (var kvp in htmlAttributes.GetType().GetProperties()
.ToDictionary(p => p.Name, p => p.GetValue(htmlAttributes, null)))
{
returnText += string.Format(" {0}=\"{1}\"", HttpUtility.HtmlEncode(kvp.Key),
HttpUtility.HtmlEncode(kvp.Value.ToStringOrEmpty()));
}
}
returnText += ">\n";
if (blankFirstLine)
{
returnText += "<option value=\"\"></option>";
}
//build the options tags
foreach (var enumName in Enum.GetNames(typeof(TProperty)))
{
var idValue = ((int)Enum.Parse(typeof(TProperty), enumName, true)).ToString();
var displayValue = enumName;
var titleValue = string.Empty;
returnText += string.Format("<option value=\"{0}\" title=\"{1}\"",
HttpUtility.HtmlEncode(idValue), HttpUtility.HtmlEncode(titleValue));
if (enumName == propertyValue)
{
returnText += " selected=\"selected\"";
}
returnText += string.Format(">{0}</option>\n", HttpUtility.HtmlEncode(displayValue));
}
//close the select tag
returnText += "</select>";
return new HtmlString(returnText);
}
现在,我有了一个好主意,“我知道!我将使用数据注释!”。。。所以我让我的枚举看起来像这样:
public enum EmployeeTypes
{
[Display(Name = "Full Time")]
FullTime = 1,
[Display(Name = "Part Time")]
PartTime,
[Display(Name = "Vendor")]
Vendor,
[Display(Name = "Contractor")]
Contractor
}
。。。但是现在我正在琢磨如何在助手类中访问这些属性。有人能让我继续吗?您可以使用循环内的反射从枚举字段读取
DisplayAttribute
:
foreach (var enumName in Enum.GetNames(typeof(TProperty)))
{
var idValue = ((int)Enum.Parse(typeof(TProperty), enumName, true)).ToString();
var displayValue = enumName;
// get the corresponding enum field using reflection
var field = typeof(TProperty).GetField(enumName);
var display = ((DisplayAttribute[])field.GetCustomAttributes(typeof(DisplayAttribute), false)).FirstOrDefault();
if (display != null)
{
// The enum field is decorated with the DisplayAttribute =>
// use its value
displayValue = display.Name;
}
var titleValue = string.Empty;
returnText += string.Format("<option value=\"{0}\" title=\"{1}\"",
HttpUtility.HtmlEncode(idValue), HttpUtility.HtmlEncode(titleValue));
if (enumName == propertyValue)
{
returnText += " selected=\"selected\"";
}
returnText += string.Format(">{0}</option>\n", HttpUtility.HtmlEncode(displayValue));
}
foreach(Enum.GetNames中的变量enumName(typeof(TProperty)))
{
var idValue=((int)Enum.Parse(typeof(TProperty),enumName,true)).ToString();
var displayValue=enumName;
//使用反射获取相应的枚举字段
var field=typeof(TProperty).GetField(enumName);
var display=((DisplayAttribute[])field.GetCustomAttributes(typeof(DisplayAttribute),false)).FirstOrDefault();
如果(显示!=null)
{
//枚举字段用DisplayAttribute=>
//利用它的价值
displayValue=display.Name;
}
var titleValue=string.Empty;
returnText+=string.Format(“{0}\n”,HttpUtility.HtmlEncode(displayValue));
}
您可以使用循环内的反射从枚举字段读取显示属性
:
foreach (var enumName in Enum.GetNames(typeof(TProperty)))
{
var idValue = ((int)Enum.Parse(typeof(TProperty), enumName, true)).ToString();
var displayValue = enumName;
// get the corresponding enum field using reflection
var field = typeof(TProperty).GetField(enumName);
var display = ((DisplayAttribute[])field.GetCustomAttributes(typeof(DisplayAttribute), false)).FirstOrDefault();
if (display != null)
{
// The enum field is decorated with the DisplayAttribute =>
// use its value
displayValue = display.Name;
}
var titleValue = string.Empty;
returnText += string.Format("<option value=\"{0}\" title=\"{1}\"",
HttpUtility.HtmlEncode(idValue), HttpUtility.HtmlEncode(titleValue));
if (enumName == propertyValue)
{
returnText += " selected=\"selected\"";
}
returnText += string.Format(">{0}</option>\n", HttpUtility.HtmlEncode(displayValue));
}
foreach(Enum.GetNames中的变量enumName(typeof(TProperty)))
{
var idValue=((int)Enum.Parse(typeof(TProperty),enumName,true)).ToString();
var displayValue=enumName;
//使用反射获取相应的枚举字段
var field=typeof(TProperty).GetField(enumName);
var display=((DisplayAttribute[])field.GetCustomAttributes(typeof(DisplayAttribute),false)).FirstOrDefault();
如果(显示!=null)
{
//枚举字段用DisplayAttribute=>
//利用它的价值
displayValue=display.Name;
}
var titleValue=string.Empty;
returnText+=string.Format(“{0}\n”,HttpUtility.HtmlEncode(displayValue));
}
我一直非常喜欢为Enum类创建一个扩展方法来读取Description属性,并对任何枚举调用ToDescription()。像这样的
public static class EnumExtensions
{
public static String ToDescription(this Enum value)
{
FieldInfo field = value.GetType().GetField(value.ToString());
DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
return attribute == null ? value.ToString() : attribute.Description;
}
}
我一直非常喜欢为Enum类创建一个扩展方法来读取Description属性,并对所有Enum调用ToDescription()。像这样的
public static class EnumExtensions
{
public static String ToDescription(this Enum value)
{
FieldInfo field = value.GetType().GetField(value.ToString());
DescriptionAttribute attribute = Attribute.GetCustomAttribute(field, typeof(DescriptionAttribute)) as DescriptionAttribute;
return attribute == null ? value.ToString() : attribute.Description;
}
}
Jeremy,“.ToStringOrEmpty”是什么?抱歉,那只是我用来处理空值的助手。。。将null转换为空字符串,否则返回对象的
ToString()
方法。Jeremy,“.ToString空”是什么?抱歉,这只是我用来处理null的助手。。。将null转换为空字符串,否则返回对象的ToString()
method.Beautiful。我会尝试一下,然后再给你回复。我已经尝试过:-)希望它也能对你起作用。达林,你无处不在!您的解决方案一如既往地非常好:DBeautiful。我会尝试一下,然后再给你回复。我已经尝试过:-)希望它也能对你起作用。达林,你无处不在!和往常一样,你的解决方案很好:D