【问题标题】:How to create custom taghelper in donet core 2.1 [closed]如何在 dotnet core 2.1 中创建自定义标签助手 [关闭]
【发布时间】:2018-10-05 00:39:15
【问题描述】:

我正在 dot net core2.1 上创建一个 MVC 应用程序。我试图为 razor 创建一个 html 和 ajax taghelper。我正在创建图像 actionlink。我之前已经在 .net MVC 5 上使用扩展方法完成了此操作,但在 dot net core 中我无法理解。任何人都可以帮助实现这一点,因为我只是一个初学者。

【问题讨论】:

    标签: razor asp.net-core-2.1


    【解决方案1】:

    首先,我建议您查看the official document,了解如何创建TagHelper。如果您仍然感到困惑,请不要担心,我会向您展示一个更简单的解释。

    TagHelper 只不过是一段有助于在 Razor 中呈现 HTML 元素的服务器端代码。使TagHelper 更强大的是我们可以向其中注入配置和服务。

    我们以一张图片为例。假设我们想要一个魔术<magic-image>,它将被渲染为

    <img src="localserver-url" />
    

    开发时,会渲染成

    <img src="cdn-url" />
    

    在生产环境中。这里输入是src,输出是&lt;img src=''&gt;

    您只需要记住 4 条规则:

    1. 我们可以使用[HtmlTargetElement("magic-image")]告诉编译器它将被用作&lt;magic-image &gt;
    2. 我们可以定义尽可能多的属性来接收用户输入。例如,我们在这里使用Src 来保存来自用户的相对网址:&lt;magic-image src='xxx'&gt;
    3. 我们可以将 DI 与 TagHelper 一起使用。换句话说,我们可以注入服务和配置/选项。
    4. Process() 方法用于将输入映射到最终输出。我们可以设置 output.TagName 、 innerHtml ,就像我们过去使用 javascript 操作 DOM 的方式一样。

    由于我们需要根据当前环境计算最终的src,让我们创建一个TagHelper,并注入一个Configuration

    [HtmlTargetElement("magic-image")]
    public class MagicImageTagHelper : TagHelper
    {
        public IConfiguration Configuration{ get; set; } 
        public MagicImageTagHelper(IConfiguration configuration) {
            this.Configuration = configuration;
        }
    
        // the `Src` here will be set by user in this way : `<magic-image src="xxxx">`
        public string Src { get; set; }
    
        // how to map the `<magic-image src="xxx">` to the final output
        public override void Process(TagHelperContext context, TagHelperOutput output)
        {
            output.TagName = "img";    // the element will be <img>
    
            // ...
            // get cdn base url string from configration , 
            var CdnUrlBase = Configuration["CdnUrl"];
    
            var src=CdnUrlBase + Src; 
    
            output.Attributes.SetAttribute("src", src);   // set the `img.src`
        }
    }
    

    【讨论】:

    • 感谢您的建议和指导。我开始查看官方文档并很快更新了一个示例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-03-05
    • 1970-01-01
    • 2015-08-01
    • 2019-11-07
    • 1970-01-01
    • 2011-08-06
    • 2013-02-14
    相关资源
    最近更新 更多