免責聲明:以下的作品只能用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
。
UPDATE:
我以前的答案將不會與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
...
}
謝謝!但是這不起作用,DisplayName和Description是空的?請注意,這是在MVC2而不是MVC3。如果我解決了這個問題,你的解決方案只能在MVC3中使用? – Banshee 2011-02-11 21:04:53