免责声明:以下内容仅适用于 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")]
and [Display(Name = "bar")]
在同一模型属性上是多余的,并且在[Display]
属性优先于metadata.DisplayName
.
UPDATE:
我之前的答案不适用于 ASP.NET MVC 2.0。有几个属性无法默认填充DataAnnotations
在 .NET 3.5 中,以及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
...
}