Populate a Razor Section From a Partial

前端 未结 12 1530
不知归路
不知归路 2020-11-27 11:23

My main motivation for trying to do this is to get Javascript that is only required by a partial at the bottom of the page with the rest of the Javascript and not in the mid

12条回答
  •  广开言路
    2020-11-27 12:01

    For those looking for the aspnet core 2.0 version:

        using System.Collections.Generic;
        using System.Linq;
        using System.Text;
        using Microsoft.AspNetCore.Html;
        using Microsoft.AspNetCore.Http;
    
        public static class HttpContextAccessorExtensions
        {
            public static string RequireScript(this IHttpContextAccessor htmlContextAccessor, string path, int priority = 1)
            {
                var requiredScripts = htmlContextAccessor.HttpContext.Items["RequiredScripts"] as List;
                if (requiredScripts == null) htmlContextAccessor.HttpContext.Items["RequiredScripts"] = requiredScripts = new List();
                if (requiredScripts.All(i => i.Path != path)) requiredScripts.Add(new ResourceInclude() { Path = path, Priority = priority });
                return null;
            }
    
            public static HtmlString EmitRequiredScripts(this IHttpContextAccessor htmlContextAccessor)
            {
                var requiredScripts = htmlContextAccessor.HttpContext.Items["RequiredScripts"] as List;
                if (requiredScripts == null) return null;
                StringBuilder sb = new StringBuilder();
                foreach (var item in requiredScripts.OrderByDescending(i => i.Priority))
                {
                    sb.AppendFormat("\n", item.Path);
                }
                return new HtmlString(sb.ToString());
            }
            public class ResourceInclude
            {
                public string Path { get; set; }
                public int Priority { get; set; }
            }
        }
    

    Add to your layout after the scripts render section call:

    @HttpContextAccessor.EmitRequiredScripts()
    

    And in your partial view:

    @inject IHttpContextAccessor HttpContextAccessor
    
    ...
    
    @HttpContextAccessor.RequireScript("/scripts/moment.min.js")
    

提交回复
热议问题