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

前端 未结 1 380
北荒
北荒 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<TModel, TValue>(
                                 this HtmlHelper<TModel> html,
                                 Expression<Func<TModel, TValue>> expression) {
        var data = ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, html.ViewData);
        if (data.AdditionalValues.ContainsKey("Tooltip"))
            return new HtmlString((string)data.AdditionalValues["Tooltip"]);
    
        return new HtmlString("");
    }
    
    0 讨论(0)
提交回复
热议问题