I m目前利用这一系统,将一 en变成无线电控制。
public static MvcHtmlString RadioButtonForEnum<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression)
{
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var sb = new StringBuilder();
var enumType = metaData.ModelType;
foreach (var field in enumType.GetFields(BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public))
{
var value = (int)field.GetValue(null);
var name = Enum.GetName(enumType, value);
var label = name;
foreach (DisplayAttribute currAttr in field.GetCustomAttributes(typeof(DisplayAttribute), true))
{
label = currAttr.Name;
break;
}
var id = string.Format(
"{0}_{1}_{2}",
htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix,
metaData.PropertyName,
name
);
var radio = htmlHelper.RadioButtonFor(expression, name, new { id = id }).ToHtmlString();
sb.AppendFormat(
"<label for="{0}">{1}</label> {2}",
id,
HttpUtility.HtmlEncode(label),
radio
);
}
return MvcHtmlString.Create(sb.ToString());
}
但是,在试图使其适应时,却要放弃:
public static MvcHtmlString DropDownListForEnum<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression)
{
var metaData = ModelMetadata.FromLambdaExpression(expression, htmlHelper.ViewData);
var sb = new StringBuilder();
var enumType = metaData.ModelType;
sb.Append("<select name="" + metaData.PropertyName + "" id="" + metaData.PropertyName + "" > ");
foreach (var field in enumType.GetFields(BindingFlags.Static | BindingFlags.GetField | BindingFlags.Public))
{
var value = (int)field.GetValue(null);
var name = Enum.GetName(enumType, value);
var label = name;
foreach (DisplayAttribute currAttr in field.GetCustomAttributes(typeof(DisplayAttribute), true))
{
label = currAttr.Name;
break;
}
var id = string.Format(
"{0}_{1}_{2}",
htmlHelper.ViewData.TemplateInfo.HtmlFieldPrefix,
metaData.PropertyName,
name
);
var listitem = htmlHelper.DropDownListFor(expression, name, new { id = id }).ToHtmlString();
sb.AppendFormat(
"<option value="{0}_{1}">{2}</option> ",
id,
listitem,
HttpUtility.HtmlEncode(label)
);
}
sb.Append("</select>");
return MvcHtmlString.Create(sb.ToString());
}
在<代码>var listitem = htmlHelper.DropDownListFor线上,我发现了一个错误。 基本上,Im没有以这种方法提供正确信息。 是否有人对此问题有任何了解?