How to render scripts, generated in TagHelper process method, to the bottom of the page rather than next to the tag element?

后端 未结 7 1427
情深已故
情深已故 2020-12-11 06:28

I am generating scripts in process method of TagHelper class as follows

[TargetElement(\"MyTag\")]
    public Class MYClass: TagHelper{
      public override         


        
7条回答
  •  我在风中等你
    2020-12-11 07:10

    I have created a pair of custom tag helpers that are able to solve your problem.

    The first one is and it just stores the html content wrapped inside it in the TempData dictionary. It provides no direct output. The content may be an inline script or any other html. Many tag helpers of this kind can be placed in various locations e.g. in partial views.

    The second tag helper is and it renders all the previously stored contents at the desired location e.g at the end of body element.

    Code for StoreContentTagHelper.cs:

    using System;
    using System.Collections.Generic;
    using System.Threading.Tasks;
    using Microsoft.AspNet.Mvc;
    using Microsoft.AspNet.Mvc.Rendering;
    using Microsoft.AspNet.Razor.Runtime.TagHelpers;
    
    
    namespace YourProjectHere.TagHelpers
    {
        [TargetElement("storecontent", Attributes = KeyAttributeName)]
        public class StoreContentTagHelper : TagHelper
        {
            private const string KeyAttributeName = "asp-key";
            private const string _storageKey = "storecontent";
            private const string _defaultListKey = "DefaultKey";
    
            [HtmlAttributeNotBound]
            [ViewContext]
            public ViewContext ViewContext { get; set; }
    
            [HtmlAttributeName(KeyAttributeName)]
            public string Key { get; set; }
    
            public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
            {
                output.SuppressOutput();
                TagHelperContent childContent = await context.GetChildContentAsync();
    
                var storageProvider = ViewContext.TempData;
                Dictionary> storage;
                List defaultList;
    
                if (!storageProvider.ContainsKey(_storageKey) || !(storageProvider[_storageKey] is Dictionary>))
                {
                    storage = new Dictionary>();
                    storageProvider[_storageKey] = storage;
                    defaultList = new List();
                    storage.Add(_defaultListKey, defaultList);
                }
                else
                {
                    storage = ViewContext.TempData[_storageKey] as Dictionary>;
                    if (storage.ContainsKey(_defaultListKey))
                    {
                        defaultList = storage[_defaultListKey];
    
                    }
                    else
                    {
                        defaultList = new List();
                        storage.Add(_defaultListKey, defaultList);
                    }
                }
    
                if (String.IsNullOrEmpty(Key))
                {
                    defaultList.Add(new HtmlString(childContent.GetContent()));
                }
                else
                {
                    if(storage.ContainsKey(Key))
                    {
                        storage[Key].Add(new HtmlString(childContent.GetContent()));
                    }
                    else
                    {
                        storage.Add(Key, new List() { new HtmlString(childContent.GetContent()) });
                    }
                }
            }
        } 
    } 
    

    Code for RenderStoredContentTagHelper.cs:

    using System;
    using System.Linq;
    using System.Collections.Generic;
    using Microsoft.AspNet.Mvc;
    using Microsoft.AspNet.Mvc.Rendering;
    using Microsoft.AspNet.Razor.Runtime.TagHelpers;
    
    
    namespace YourProjectHere.TagHelpers
    {
        [TargetElement("renderstoredcontent", Attributes = KeyAttributeName)]
        public class RenderStoredContentTagHelper : TagHelper
        {
            private const string KeyAttributeName = "asp-key";
            private const string _storageKey = "storecontent";
    
            [HtmlAttributeNotBound]
            [ViewContext]
            public ViewContext ViewContext { get; set; }
    
            [HtmlAttributeName(KeyAttributeName)]
            public string Key { get; set; }
    
            public override void Process(TagHelperContext context, TagHelperOutput output)
            {
                output.TagName = String.Empty;
    
                var storageProvider = ViewContext.TempData;
                Dictionary> storage;
    
                if (!storageProvider.ContainsKey(_storageKey) || !(storageProvider[_storageKey] is Dictionary>))
                {
                    return;
                }
    
                storage = storageProvider[_storageKey] as Dictionary>;
                string html = "";
    
                if (String.IsNullOrEmpty(Key))
                {
                    html = String.Join("", storage.Values.SelectMany(x => x).ToList());
                }
                else
                {
                    if (!storage.ContainsKey(Key)) return;
                    html = String.Join("", storage[Key]);
                }
    
                TagBuilder tagBuilder = new TagBuilder("dummy");
                tagBuilder.InnerHtml = html;
                output.Content.SetContent(tagBuilder.InnerHtml);
            }
        } 
    } 
    

    Basic usage:

    In some view or partial view:

    
      
    
    

    In another location:

    
      
    
    

    And finally at the desired location where both scripts should be rendered:

    
    

    That's it.

    A few notes:

    1. There can be any number of tags. The asp-key attribute is required, at least as empty "". If you specify specific values for this attribute you can group the stored content and render specific groups at different locations. E.g. if you specify some content with asp-key="scripts" and some other content with asp-key="footnotes" then you can render only the first group as some location using:

    The other group "footnotes" can be rendered at another location.

    1. The must be defined before the is applied. In ASP.NET the response is generated in a reverse hierarchical order, firstly the innermost partial views are generated, then the parent partial view, then the main view and finally the layout page. Therefore you can easily use these tag helpers to define scripts in a partial view and then render the scripts at the end of the body section in the layout page.

    2. Don't forget to reference your custom tag helpers in the _ViewImports.cshtml file using the command @addTagHelper "*, YourProjectHere"

    Sorry for the long post, and I hope it helps!

提交回复
热议问题