手动实例化和调用TagHelpers [英] Instantiating and Invoking TagHelpers Manually

查看:144
本文介绍了手动实例化和调用TagHelpers的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是对这个问题,似乎是针对较旧的ASP.NET Core版本(我正在使用2.1)。

This is a follow up question to this question, which seems to be for an older ASP.NET Core version (I'm using 2.1).

我正在尝试从TagHelper内部手动调用TagHelper。在上面的链接问题中应用答案,TagHelper.Process看起来像这样:

I'm trying to call a TagHelper manually from within a TagHelper. Applying the Answer in the linked question above, the TagHelper.Process looks like so:

public override async void Process(TagHelperContext context, TagHelperOutput output)
{
    var anchorTagHelper = new AnchorTagHelper
    {
        Action = "Home",
    };
    var anchorOutput = new TagHelperOutput("a", new TagHelperAttributeList(), (useCachedResult, encoder) => new HtmlString());
    var anchorContext = new TagHelperContext(
        new TagHelperAttributeList(new[] { new TagHelperAttribute("asp-action", new HtmlString("Home")) }),
        new Dictionary<object, object>(),
        Guid.NewGuid());
    await anchorTagHelper.ProcessAsync(anchorContext, anchorOutput);
    output.Content.SetHtmlContent(anchorOutput);
}

此时会发生几个编译器错误。

Several compiler errors occur at this point.


无法从'System.Guid'转换为'string'

cannot convert from 'System.Guid' to 'string'

没问题,我可以转换为字符串。

No problem, I can cast to a String.


没有给定对应于'HtmlString.HtmlString(string)<的必需形式
参数'value'的参数/ p>

There is no argument given that corresponds to the required formal parameter 'value' of 'HtmlString.HtmlString(string)

检查MSDN页面中的 TagHelperOutput构造,现在看来,这并不需要一个 HtmlString 了。

Checking the MSDN page for the TagHelperOutput constructor, it seems it doesn't take an HtmlString anymore.

我将该参数更改为委托函数:

I changed that argument to a delegate fuction:

new TagHelperOutput("a", new TagHelperAttributeList(),
    (useCachedResult, encoder) => Task.Factory.StartNew<TagHelperContent>(
         () => new DefaultTagHelperContent()));

最后一个编译器错误:


没有给定对应于
'AnchorTagHelper.AnchorTagHelper(IHtmlGenerator)

There is no argument given that corresponds to the required formal parameter 'generator' of 'AnchorTagHelper.AnchorTagHelper(IHtmlGenerator)

$
的形式
参数'generator'的自变量b
$ b

希望它是一个可选参数,我传入了null:

Hoping its an optional parameter, I passed in null:

var anchorTagHelper = new AnchorTagHelper(null);






最终编译-但这导致了null运行时指针异常:


It finally compiled - but this led to a null pointer exception on runtime:


Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper.Process(TagHelperContext
context,TagHelperOutput输出)

Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper.Process(TagHelperContext context, TagHelperOutput output)

因此,我的问题是:如何实例化 a ?所以我可以在C#中手动调用TagHelpers?

My question is thus: how can I instantiate AnchorTagHelper so I can manually invoke TagHelpers in C#?

编辑:我将IHtmlGenerator进行了DI处理,并得到了更有意义的错误消息:

EDIT: I've DI'd IHtmlGenerator and got a more meaningful error message:

private IHtmlGenerator htmlGenerator;
public myAnchorTagHelper(IHtmlGenerator htmlGenerator) {
    this.htmlGenerator = htmlGenerator;
}




值不能为null。参数名称:viewContext>

Value cannot be null. Parameter name: viewContext>

Microsoft.AspNetCore.Mvc.ViewFeatures.DefaultHtmlGenerator.GenerateActionLink(ViewContext
viewContext,String linkText,String actionName,String
controllerName,String协议,String主机名,String片段,
处的
对象routeValues,对象htmlAttributes),位于$ b处Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper.Process(TagHelperContext
上下文,TagHelperOutput输出) b $ b EAGLEweb2020.Models.EAGLEinputTagHelper.Process(TagHelperContext
context,TagHelperOutput输出)在
中C:\Users\1135937\source\repos\EAGLEweb2020\EAGLEweb2020\Models\ HelpTagHelpers\EAGLEinputTagHelper.cs:

66 Microsoft.AspNetCore.Razor.TagHelpers.TagHelper.ProcessAsync(TagHelperContext
context,TagHelperOutput输出)在
Microsoft.AspNetCore。 Razor.Runtime.TagHelpers.TagHelperRunner.d__0.MoveNext()

Microsoft.AspNetCore.Mvc.ViewFeatures.DefaultHtmlGenerator.GenerateActionLink(ViewContext viewContext, String linkText, String actionName, String controllerName, String protocol, String hostname, String fragment, Object routeValues, Object htmlAttributes) at Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper.Process(TagHelperContext context, TagHelperOutput output) at EAGLEweb2020.Models.EAGLEinputTagHelper.Process(TagHelperContext context, TagHelperOutput output) in C:\Users\1135937\source\repos\EAGLEweb2020\EAGLEweb2020\Models\TagHelpers\EAGLEinputTagHelper.cs:line 66 at Microsoft.AspNetCore.Razor.TagHelpers.TagHelper.ProcessAsync(TagHelperContext context, TagHelperOutput output) at Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner.d__0.MoveNext()

但是我如何为ViewContext设置DI?

But how can I DI a ViewContext?

编辑2:

结果是ViewContext是AnchorTagHelper中的公共属性:

Turns out ViewContext is a public property in AnchorTagHelper:

AnchorTagHelper inputTagHelper = new AnchorTagHelper(htmlGenerator);
inputTagHelper.ViewContext = viewContext;

但是现在内容为空...

But now the content is empty...

推荐答案

我正在研究这个问题,但您陷入了ViewContext和输出的困境。
我也做了类似的项目。这是代码,希望对您有所帮助。

Hi I was going through this and you got stuck at the ViewContext and the Output. I have done a similar project. Here's the code, hope it helps.

[HtmlTargetElement(ParentAnchorTag)]
public class ParentActionTagHelper : TagHelper
{
    private const string ParentAnchorTag = "p-a";

    [HtmlAttributeNotBound]
    [ViewContext]
    public ViewContext viewContext { get; set; }

    private readonly IHtmlGenerator _htmlGenerator;

    public ParentActionTagHelper(IHtmlGenerator htmlGenerator)
    {
        _htmlGenerator = htmlGenerator;
    }
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        output.TagName = "div";

        var anchorTagHelper = new AnchorTagHelper(_htmlGenerator)
        {
            Action = "Privacy",
            ViewContext = viewContext,

        };
        var anchorOutput = new TagHelperOutput("a", new TagHelperAttributeList(),
            (useCachedResult, encoder) =>  Task.Factory.StartNew<TagHelperContent>(
                 () => new DefaultTagHelperContent()));
        anchorOutput.Content.AppendHtml("Privacy Link");
        var anchorContext = new TagHelperContext(
            new TagHelperAttributeList(new[]
            {
                new TagHelperAttribute("asp-action", new HtmlString("Privacy"))
            }),
                new Dictionary<object, object>(),
                Guid.NewGuid().ToString());

        anchorTagHelper.ProcessAsync(anchorContext, anchorOutput).GetAwaiter().GetResult();
        output.Content.SetHtmlContent(anchorOutput);
    }
}

这篇关于手动实例化和调用TagHelpers的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆