该[Display]
属性丰富了元数据。因此,您可以从元数据中获取信息。
例如,如果您想在帮助程序中检索显示名称:
public static class HtmlHelpers
{
public static IHtmlString Example<TModel, TProperty>(
this HtmlHelper<TModel> html,
Expression<Func<TModel, TProperty>> ex
)
{
var metadata = ModelMetadata.FromLambdaExpression(ex, html.ViewData);
var displayName = metadata.DisplayName;
return new HtmlString(html.Encode(displayName));
}
}
然后如果我们假设您有一个视图模型:
public class MyViewModel
{
[Required]
[Display(Name = "Your Lastname")]
public string Lastname { get; set; }
}
您可以在强类型视图中使用帮助程序:
@model MyViewModel
@Html.Example(x => x.Lastname)
现在让我们假设您编写了一个自定义元数据属性:
public class FooBarAttribute : Attribute, IMetadataAware
{
public FooBarAttribute(string bar)
{
Bar = bar;
}
public string Bar { get; private set; }
public void OnMetadataCreated(ModelMetadata metadata)
{
metadata.AdditionalValues["foo"] = Bar;
}
}
你用来装饰你的模型的:
public class MyViewModel
{
[Required]
[FooBar("This is the bar")]
public string SomeBar { get; set; }
}
然后在您的助手中,您可以获取自定义属性:
public static class HtmlHelpers
{
public static IHtmlString Example<TModel, TProperty>(
this HtmlHelper<TModel> html,
Expression<Func<TModel, TProperty>> ex
)
{
var metadata = ModelMetadata.FromLambdaExpression(ex, html.ViewData);
if (metadata.AdditionalValues.ContainsKey("foo"))
{
var foo = metadata.AdditionalValues["foo"] as string;
return new HtmlString(html.Encode(foo));
}
return MvcHtmlString.Empty;
}
}
更新:
看来您需要获取所需的消息。不知道为什么需要在自定义助手中执行此操作,但这里有一个示例,您可以如何实现这一点:
public static class HtmlHelpers
{
public static IHtmlString Example<TModel, TProperty>(
this HtmlHelper<TModel> html,
Expression<Func<TModel, TProperty>> ex
)
{
var me = (ex.Body as MemberExpression);
if (me != null)
{
var required = me
.Member
.GetCustomAttributes(typeof(RequiredAttribute), false)
.Cast<RequiredAttribute>()
.FirstOrDefault();
if (required != null)
{
var msg = required.FormatErrorMessage(me.Member.Name);
return new HtmlString(html.Encode(msg));
}
}
return MvcHtmlString.Empty;
}
}