Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get element's (defined as TagHelper) content in TagHelper.Process?

How to get elements defined as TagHelper content?

E.g. element defined as:

<markdown>bla bla</markdown>

And helper defined as:

[HtmlTargetElement("markdown")]
public class MarkdownTagHelper : TagHelper
{
    public override void Process(TagHelperContext context, TagHelperOutput output)
    {
        var c = output.Content.GetContent(); 
        // c is empty; how to get content "bla bla"?
    }
}
like image 996
Roman Pokrovskij Avatar asked Nov 28 '16 17:11

Roman Pokrovskij


People also ask

What is the difference between Htmlhelper and Taghelper?

HtmlHelpers vs. Unlike HtmlHelpers, a tag helper is a class that attaches itself to an HTML-compliant element in a View or Razor Page. The tag helper can, through its properties, add additional attributes to the element that a developer can use to customize the tag's behavior.

How might you supply data from a database into a tag helper's output?

Passing a model Data to a Tag Helper We can also pass the model data to the tag helper via model binding by creating properties of type "ModelExpression". Using HtmlAttributeName attribute, we can create a friendly attribute name. The ModelExpression describes a model expression passed to the tag helper.

How would you use the input tag helper to bind an input element to an expression in a Razor view file?

The Input Tag Helper binds an HTML <input> element to a model expression in your razor view. The Input Tag Helper: Generates the id and name HTML attributes for the expression name specified in the asp-for attribute. asp-for="Property1.

How would the form tag helper create a form element for posting data back to the server?

The Form Tag Helper targets the HTML <form> element and generates the action URL & action method attributes. It uses the various server-side attributes like asp-controller, asp-action, asp-route- etc to generate the <form> element in the view.


1 Answers

You can use output.GetChildContentAsync() as explained in the docs (worth reading as it contains a few examples that retrieve the element's contents).

You will then implement your tag helper as in:

public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
      var c = (await output.GetChildContentAsync()).GetContent(); 
      // transform markdown in c
}
like image 72
Daniel J.G. Avatar answered Oct 16 '22 03:10

Daniel J.G.