这不是那么简单,因为DataAnnotationsModelMetadataProvider(名称!)不使用Description属性。
因此,要使用Description属性,您需要执行以下操作:
创建自定义ModelMetaDataProvider。
将其注册为应用程序的元数据提供程序。
实施DescriptionFor方法。
所以...
这是自定义ModelMetaDataProvider:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.ComponentModel;
namespace MvcApplication2
{
public class DescriptionModelMetaDataProvider : DataAnnotationsModelMetadataProvider
{
protected override ModelMetadata CreateMetadata(IEnumerable attributes, Type containerType, Func modelAccessor, Type modelType, string propertyName)
{
ModelMetadata result = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
DescriptionAttribute descriptionAttribute = attributes.OfType().FirstOrDefault();
if (descriptionAttribute != null)
result.Description = descriptionAttribute.Description;
return result;
}
}
}现在,注册它是在Application_Start方法中的Global.asax文件中完成的,如下所示:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
// This is the important line:
ModelMetadataProviders.Current = new DescriptionModelMetaDataProvider();
}最终,DescriptionFor方法的实现:
using System.Linq.Expressions;
namespace System.Web.Mvc.Html
{
public static class Helper
{
public static MvcHtmlString DescriptionFor(this HtmlHelper html, Expression> expression)
{
ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
string fieldName = ExpressionHelper.GetExpressionText(expression);
return MvcHtmlString.Create(String.Format("{1}",
html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(fieldName),
metadata.Description));// Here goes the description
}
}
}这应该工作,我在我的机器上检查了它。
吉文。