Nesting TagHelpers in ASP.NET Core MVC

后端 未结 2 1134
你的背包
你的背包 2020-12-06 06:49

The ASP.NET Core TagHelper documentation gives the following example:

public class WebsiteContext
{
    public Version Version { get; set; }
    public int C         


        
2条回答
  •  执念已碎
    2020-12-06 06:54

    I did not find a good example of multiply nested tag helpers on the web; so, I created one at MultiplyNestedTagHelpers GitHub Repository.

    When working with more than one level of nested tag helper, it is important to setup a "context" class for each tag that can contain child tags. These context classes are used by the child tags to write their output. The context class is a regular, POCO class that has a property for each child tag. The properties may be strings, but I use StringBuilder. For example,

    public class MyTableContext{
        public StringBuilder TableHeaderBuilder { get; set; } = new StringBuilder();
        public StringBuilder TableBodyBuilder { get; set; } = new StringBuilder();
    }
    public class MyTableHeaderContext {
        public StringBuilder RowBuilder { get; set; } = new StringBuilder();
    }
    //...etc.
    

    In each parent tag's Process method, you need to instantiate the parent's associated context class and add this new object to the TagHelperContext object's Items collection. For example:

        //create context for this tag helper
        var tableContext = new MyTableContext();
        context.Items.Add(typeof(MyTableContext), tableContext);
    

    In the child tag's Process method, you write to the parent's registered context object like this:

        //get reference to parent context, and append content to the relevant builder
        var tableContext = context.Items[typeof(MyTableContext)] as MyTableContext;
        tableContext.TableHeaderBuilder.Append(sb.ToString());
    
        //suppress output (for any tag with a parent tag)
        output.SuppressOutput();
    

    Back in the parent tag's Process method, you receive the child tag's output like this:

        //you can use a StringBuilder to build output 
        //    or just write to output.Content.AppendHtml() for top-level tags
        var sb = new StringBuilder();
        //...      
    
        //retrieve the child output and append it to sb
        await output.GetChildContentAsync();
        sb.Append(tableHeaderContext.RowBuilder.ToString());
        //...
    
        //write to TagHelperOutput for top-level tags      
        output.Content.AppendHtml(sb.ToString());
    

提交回复
热议问题