Injecting content into specific sections from a partial view ASP.NET MVC 3 with Razor View Engine

后端 未结 24 1648
无人共我
无人共我 2020-11-22 06:13

I have this section defined in my _Layout.cshtml

@RenderSection(\"Scripts\", false)

I can easily use it from a view:

24条回答
  •  不思量自难忘°
    2020-11-22 07:00

    Using Mvc Core you can create a tidy TagHelper scripts as seen below. This could easily be morphed into a section tag where you give it a name as well (or the name is taken from the derived type). Note that dependency injection needs to be setup for IHttpContextAccessor.

    When adding scripts (e.g. in a partial)

    
        
    
    

    When outputting the scripts (e.g. in a layout file)

    
    

    Code

    public class ScriptsTagHelper : TagHelper
        {
            private static readonly object ITEMSKEY = new Object();
    
            private IDictionary _items => _httpContextAccessor?.HttpContext?.Items;
    
            private IHttpContextAccessor _httpContextAccessor;
    
            public ScriptsTagHelper(IHttpContextAccessor httpContextAccessor)
            {
                _httpContextAccessor = httpContextAccessor;
            }
    
            public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
            {
                var attribute = (TagHelperAttribute)null;
                context.AllAttributes.TryGetAttribute("render",out attribute);
    
                var render = false;
    
                if(attribute != null)
                {
                    render = Convert.ToBoolean(attribute.Value.ToString());
                }
    
                if (render)
                {
                    if (_items.ContainsKey(ITEMSKEY))
                    {
                        var scripts = _items[ITEMSKEY] as List;
    
                        var content = String.Concat(scripts);
    
                        output.Content.SetHtmlContent(content);
                    }
                }
                else
                {
                    List list = null;
    
                    if (!_items.ContainsKey(ITEMSKEY))
                    {
                        list = new List();
                        _items[ITEMSKEY] = list;
                    }
    
                    list = _items[ITEMSKEY] as List;
    
                    var content = await output.GetChildContentAsync();
    
                    list.Add(new HtmlString(content.GetContent()));
                }
            }
        }
    

提交回复
热议问题