Access displayName attribute from the model in MVC View

前端 未结 8 709
不思量自难忘°
不思量自难忘° 2021-02-06 22:51

If my model have

[DisplayName(\"First Name\")]
public string firstName { get; set; }

Then I can print it in the View with LabelFor



        
8条回答
  •  谎友^
    谎友^ (楼主)
    2021-02-06 23:32

    To access the attributes you'll need a custom Html helper. Since the attributes aren't really part of the property or model you need to go in a round about way to access them.

    public static IHtmlString DisplayName(
                                 this HtmlHelper html,
                                 Expression> expression) {
        var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
    
        return new HtmlString(metadata.DisplayName);
    }
    

    For additional attributes that aren't part of the DataAnnotations you can do the following:

    Create a custom attribute

    public class TooltipAttribute : Attribute, IMetadataAware {
        public TooltipAttribute(string tooltip) {
            this.Tooltip = tooltip;
        }
    
        public string Tooltip { get; set; }
    
        public void OnMetadataCreated(ModelMetadata metadata) {
            metadata.AdditionalValues["Tooltip"] = this.Tooltip;
        }
    }
    

    The magic happens in the OnMetadataCreated implementation. Here we can populate the AdditionalValues with anything we need for our particular Attribute. In this case we’re adding a Tooltip key. Your name should be unique as other attributes or providers may add their own keys with the same name It is important to remember that attributes are not always read in the same order. So your tooltip attribute may be called first, last or somewhere in the middle. This is an important distinction as it may cause undesired effects.

    Then create a custom Attribute helper

    public static IHtmlString TooltipFor(
                                 this HtmlHelper html,
                                 Expression> expression) {
        var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
        if (metadata.AdditionalValues.ContainsKey("Tooltip"))
            return new HtmlString((string)metadata.AdditionalValues["Tooltip"]);
    
        return new HtmlString("");
    }
    

提交回复
热议问题