Html.DescriptionFor <T>

Cie*_*iel 3 asp.net-mvc-2

我正在尝试为“ LabelFor”模拟Html Helper,以使其与[Description]属性配合使用。我在弄清楚如何从助手中获取财产时遇到了很多麻烦。这是目前的签名...

class Something
{
 [Description("Simple Description")]
 [DisplayName("This is a Display Name, not a Description!")]
 public string Name { get; set; }
}

public static MvcHtmlString DescriptionFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression);
Run Code Online (Sandbox Code Playgroud)

Sha*_*man 5

这不是那么简单,因为DataAnnotationsModelMetadataProvider(什么名字!)不使用Description属性。因此,要使用Description属性,您需要执行以下操作:

  1. 创建一个自定义ModelMetaDataProvider
  2. 将其注册为应用程序的元数据提供程序。
  3. 实现该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<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
        {
            ModelMetadata result = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);

            DescriptionAttribute descriptionAttribute = attributes.OfType<DescriptionAttribute>().FirstOrDefault();
            if (descriptionAttribute != null)
                result.Description = descriptionAttribute.Description;

            return result;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,在Application_Start方法内的Global.asax文件中完成注册,如下所示:

protected void Application_Start()
{
    AreaRegistration.RegisterAllAreas();                        
    RegisterRoutes(RouteTable.Routes);

    // This is the important line:
    ModelMetadataProviders.Current = new DescriptionModelMetaDataProvider();
}
Run Code Online (Sandbox Code Playgroud)

最终,该DescriptionFor方法的实现:

using System.Linq.Expressions;

namespace System.Web.Mvc.Html
{
    public static class Helper
    {
        public static MvcHtmlString DescriptionFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
        {
            ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
            string fieldName = ExpressionHelper.GetExpressionText(expression);

            return MvcHtmlString.Create(String.Format("<label for=\"{0}\">{1}</label>", 
                html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(fieldName),
                metadata.Description));// Here goes the description
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

应该可以,我在机器上检查了一下。

y