Html.DescriptionFor <T>

I am trying to imitate the Html Helper for "LabelFor" to work with the [Description] attribute. I have a lot of problems when I figure out how to get property from an assistant. This is the current signature ...

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);
+3
source share
1 answer

This is not so simple since DataAnnotationsModelMetadataProvider(what a name!) Does not use the Description attribute. Therefore, to use the Description attribute, you will need to do the following:

  • Create a custom one ModelMetaDataProvider.
  • Register it as an application metadata provider.
  • Implement the method DescriptionFor.

So ... Here is a custom one 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;
        }
    }
}

Global.asax Application_Start :

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<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
        }
    }
}

, .

.

+4

Source: https://habr.com/ru/post/1746714/


All Articles