How do I display the DisplayAttribute.Description attribute value?

前端 未结 12 1885
醉梦人生
醉梦人生 2020-11-27 03:26

I have a model class, with a property like this:

[Display(Name = \"Phone\", Description=\"Hello World!\")]
public string Phone1 { get; set; }
12条回答
  •  情歌与酒
    2020-11-27 04:18

    In addition to Jakob Gade'a great answer:

    If you need to Support a DescriptionAttribute instead of a DisplayAttribute, his great solution still works if we override the MetadataProvider:

    public class ExtendedModelMetadataProvider : DataAnnotationsModelMetadataProvider
    {
        protected override ModelMetadata CreateMetadata(IEnumerable attributes, Type containerType, Func modelAccessor, Type modelType, string propertyName)
        {
            //Possible Multiple Enumerations on IEnumerable fix
            var attributeList = attributes as IList ?? attributes.ToList();
    
            //Default behavior
            var data = base.CreateMetadata(attributeList, containerType, modelAccessor, modelType, propertyName);
    
            //Bind DescriptionAttribute
            var description = attributeList.SingleOrDefault(a => typeof(DescriptionAttribute) == a.GetType());
            if (description != null)
            {
                data.Description = ((DescriptionAttribute)description).Description;
            }
    
            return data;
        }
    }
    
    
    

    This need to be registeres in the Application_Start Method in Global.asax.cs:

    ModelMetadataProviders.Current = new ExtendedModelMetadataProvider();
    

    提交回复
    热议问题