免责声明:以下内容仅适用于 ASP.NET MVC 3(如果您使用的是以前的版本,请参阅底部的更新)
假设以下模型:
public class MyViewModel
{
[Display(Description = "some description", Name = "some name")]
public string SomeProperty { get; set; }
}
还有以下观点:
<%= Html.LabelFor(x => x.SomeProperty, true) %>
在您的自定义助手中,您可以从元数据中获取此信息:
public static MvcHtmlString LabelFor<TModel, TValue>(
this HtmlHelper<TModel> self,
Expression<Func<TModel, TValue>> expression,
bool showToolTip
)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, self.ViewData);
var description = metadata.Description; // will equal "some description"
var name = metadata.DisplayName; // will equal "some name"
// TODO: do something with the name and the description
...
}
备注:[DisplayName("foo")] 和 [Display(Name = "bar")] 在同一个模型属性上是多余的,[Display] 属性中使用的名称优先于 metadata.DisplayName。
更新:
我之前的回答不适用于 ASP.NET MVC 2.0。在 .NET 3.5 中,默认情况下无法使用 DataAnnotations 填充几个属性,Description 就是其中之一。要在 ASP.NET MVC 2.0 中实现这一点,您可以使用自定义模型元数据提供程序:
public class DisplayMetaDataProvider : DataAnnotationsModelMetadataProvider
{
protected override ModelMetadata CreateMetadata(
IEnumerable<Attribute> attributes,
Type containerType,
Func<object> modelAccessor,
Type modelType,
string propertyName
)
{
var metadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
var displayAttribute = attributes.OfType<DisplayAttribute>().FirstOrDefault();
if (displayAttribute != null)
{
metadata.Description = displayAttribute.Description;
metadata.DisplayName = displayAttribute.Name;
}
return metadata;
}
}
您将在Application_Start注册:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
ModelMetadataProviders.Current = new DisplayMetaDataProvider();
}
然后助手应该按预期工作:
public static MvcHtmlString LabelFor<TModel, TValue>(
this HtmlHelper<TModel> self,
Expression<Func<TModel, TValue>> expression,
bool showToolTip
)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, self.ViewData);
var description = metadata.Description; // will equal "some description"
var name = metadata.DisplayName; // will equal "some name"
// TODO: do something with the name and the description
...
}