How to use @section scripts in a partial view MVC.Core

前端 未结 2 1299
醉话见心
醉话见心 2021-02-06 18:56

In ASP.NET Core MVC it is possible to define a script section for a page like this:

@section scripts {
    

        
2条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-02-06 19:09

    Here is a solution :

    In Layout page :

    @Html.PageScripts()
    

    In the Partial :

    @using (Html.BeginScripts())
    {
     
    }
    

    And The Helper Class for MVC.core

    using Microsoft.AspNetCore.Html;
    using Microsoft.AspNetCore.Http;
    using Microsoft.AspNetCore.Mvc.Rendering;
    using System;
    using System.Collections.Generic;
    using System.IO;
    
    namespace MyProjectNamespace
    {
        public static class HtmlHelpers
        {
            private const string ScriptsKey = "DelayedScripts";
    
            public static IDisposable BeginScripts(this IHtmlHelper helper)
            {
                return new ScriptBlock(helper.ViewContext);
            }
    
            public static HtmlString PageScripts(this IHtmlHelper helper)
            {
                return new HtmlString(string.Join(Environment.NewLine, GetPageScriptsList(helper.ViewContext.HttpContext)));
            }
    
            private static List GetPageScriptsList(HttpContext httpContext)
            {
                var pageScripts = (List)httpContext.Items[ScriptsKey];
                if (pageScripts == null)
                {
                    pageScripts = new List();
                    httpContext.Items[ScriptsKey] = pageScripts;
                }
                return pageScripts;
            }
    
            private class ScriptBlock : IDisposable
            {
                private readonly TextWriter _originalWriter;
                private readonly StringWriter _scriptsWriter;
    
                private readonly ViewContext _viewContext;
    
                public ScriptBlock(ViewContext viewContext)
                {
                    _viewContext = viewContext;
                    _originalWriter = _viewContext.Writer;
                    _viewContext.Writer = _scriptsWriter = new StringWriter();
                }
    
                public void Dispose()
                {
                    _viewContext.Writer = _originalWriter;
                    var pageScripts = GetPageScriptsList(_viewContext.HttpContext);
                    pageScripts.Add(_scriptsWriter.ToString());
                }
            }
        }
    }
    

    Tip: import you class helper in _ViewImports.cshtml so you can use it in all views.

提交回复
热议问题