首页 > 解决方案 > 如何在局部视图 MVC.Core 中使用 @section 脚本

问题描述

在 ASP.NET Core MVC 中,可以为页面定义一个脚本部分,如下所示:

@section scripts {
    <script>
        alert('hello');
    </script>
}

如果布局包含:

@RenderSection("Scripts", required: false)

您的脚本将被渲染。这在每个示例中都派上用场,以保证脚本将在所有 javascript 包含(如 jQuery)之后呈现。

但是如何在局部视图中渲染脚本呢?

标签: c#asp.net-mvcasp.net-core.net-core

解决方案


这是一个解决方案:

在布局页面中:

@Html.PageScripts()

在部分:

@using (Html.BeginScripts())
{
 <script>
   alert('hello');
 </script>
}

以及 MVC.core 的 Helper 类

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<string> GetPageScriptsList(HttpContext httpContext)
        {
            var pageScripts = (List<string>)httpContext.Items[ScriptsKey];
            if (pageScripts == null)
            {
                pageScripts = new List<string>();
                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());
            }
        }
    }
}

提示:在 _ViewImports.cshtml 中导入您的类助手,以便您可以在所有视图中使用它。


推荐阅读