新建类 DescriptionMetadataProvider
然后重写DataAnnotationsModelMetadataProvider的CreateMetadata方法:
public class DescriptionMetadataProvider : DataAnnotationsModelMetadataProvider
{
protected override ModelMetadata CreateMetadata(IEnumerable<System.Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
{
List<System.Attribute> attributeList = new List<System.Attribute>(attributes);
DataAnnotationsModelMetadata result = (DataAnnotationsModelMetadata)base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);
DescriptionAttribute descriptionAttribute = attributeList.OfType<DescriptionAttribute>().FirstOrDefault();
if (descriptionAttribute != null)
{
result.Description = descriptionAttribute.Description;
}
return result;
}
}
接下来在Global.asax的Application_Start()中注册DescriptionMetadataProvider
ModelMetadataProviders.Current = new DescriptionMetadataProvider();
编译后,你就可以使用DescriptionAttribute属性了。
直接用mvc2的路过。