Is it possible to access additional metadata info from a custom display or editor template?

前端 未结 1 381
北荒
北荒 2021-01-02 07:15

I am aware that in a custom display or editor template I can get metadata about the model via ViewData.ModelMetadata, which has properties that indicate whether

1条回答
  •  一向
    一向 (楼主)
    2021-01-02 07:52

    Sure. First you'll need your attribute which implements IMetadataAware so that DataAnnotationsModelMetadataProvider knows about it

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

    You can then access the attribute by creating a helper method:

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

    0 讨论(0)
提交回复
热议问题