【发布时间】:2018-10-05 00:39:15
【问题描述】:
我正在 dot net core2.1 上创建一个 MVC 应用程序。我试图为 razor 创建一个 html 和 ajax taghelper。我正在创建图像 actionlink。我之前已经在 .net MVC 5 上使用扩展方法完成了此操作,但在 dot net core 中我无法理解。任何人都可以帮助实现这一点,因为我只是一个初学者。
【问题讨论】:
我正在 dot net core2.1 上创建一个 MVC 应用程序。我试图为 razor 创建一个 html 和 ajax taghelper。我正在创建图像 actionlink。我之前已经在 .net MVC 5 上使用扩展方法完成了此操作,但在 dot net core 中我无法理解。任何人都可以帮助实现这一点,因为我只是一个初学者。
【问题讨论】:
首先,我建议您查看the official document,了解如何创建TagHelper。如果您仍然感到困惑,请不要担心,我会向您展示一个更简单的解释。
TagHelper 只不过是一段有助于在 Razor 中呈现 HTML 元素的服务器端代码。使TagHelper 更强大的是我们可以向其中注入配置和服务。
我们以一张图片为例。假设我们想要一个魔术<magic-image>,它将被渲染为
<img src="localserver-url" />
开发时,会渲染成
<img src="cdn-url" />
在生产环境中。这里输入是src,输出是<img src=''>。
您只需要记住 4 条规则:
[HtmlTargetElement("magic-image")]告诉编译器它将被用作<magic-image >
Src 来保存来自用户的相对网址:<magic-image src='xxx'>
TagHelper 一起使用。换句话说,我们可以注入服务和配置/选项。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`
}
}
【讨论】: