新文章 网摘 文章 随笔 日记

ASP.NET Core: Section Scripts in a Partial View

块在 ASP.NET Core 中的部分视图中放置时不起作用,这与 MVC 中的功能相同 ASP.NET。不幸的是,如果您尝试将该部分添加到部分,则不会收到任何错误消息 - 它什么也不做。在许多情况下,在分部视图中具有脚本部分将是一种反模式,因为部分可以呈现未知次数。但是,有时我认为脚本部分在部分中是必要的,特别是当您尝试基于传递到部分视图的模型创建动态 JavaScript 时。虽然不能只在分部视图中使用实际,但可以添加一些 HTML 帮助程序扩展来完成相同的操作。@section Scripts@section Scripts

 

下面是实现此功能的代码 - 下面是要添加到项目中的 C# 文件中的帮助程序扩展方法:

using System;
using System.Linq;
using System.Text.Encodings.Web;
using System.Text.RegularExpressions;
using Microsoft.AspNetCore.Html;
using Microsoft.AspNetCore.Mvc.Razor;
using Microsoft.AspNetCore.Mvc.Rendering;
public static class HtmlHelperExtensions
{
    private const string _partialViewScriptItemPrefix = "scripts_";
    public static IHtmlContent PartialSectionScripts(this IHtmlHelper htmlHelper, Func<object, HelperResult> template)
    {
        htmlHelper.ViewContext.HttpContext.Items[_partialViewScriptItemPrefix + Guid.NewGuid()] = template;
        return new HtmlContentBuilder();
    }
    public static IHtmlContent RenderPartialSectionScripts(this IHtmlHelper htmlHelper)
    {
        var partialSectionScripts = htmlHelper.ViewContext.HttpContext.Items.Keys
            .Where(k => Regex.IsMatch(
                k.ToString(),
                "^" + _partialViewScriptItemPrefix + "([0-9A-Fa-f]{8}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{4}[-][0-9A-Fa-f]{12})$"));
        var contentBuilder = new HtmlContentBuilder();
        foreach (var key in partialSectionScripts)
        {
            var template = htmlHelper.ViewContext.HttpContext.Items[key] as Func<object, HelperResult>;
            if (template != null)
            {
                var writer = new System.IO.StringWriter();
                template(null).WriteTo(writer, HtmlEncoder.Default);
                contentBuilder.AppendHtml(writer.ToString());
            }
        }
        return contentBuilder;
    }
}

PartialSectionScripts在分部视图中调用,以代替您原本使用 的位置。@section Scripts

RenderPartialSectionScripts通常会在共享布局中调用,例如标准基架项目中的 _Layout.cshtml,并将呈现通过方法调用在部分中添加的任何脚本。PartialSectionScripts

下面是使用的部分视图的示例:PartialSectionScripts

@Html.PartialSectionScripts(
    @<script>
        alert('Hello from the partial view!');
    </script>
)

以及在您的共享布局中添加了该行的示例,您可能希望将其放置在正文之后和之前:RenderPartialSectionScriptsRenderSection

    @*...*@
    @RenderSection("Scripts", required: false)
    @Html.RenderPartialSectionScripts()
</body>
</html>
ASP.NET 核心:分部视图中的节脚本 (adamrussell.com)
 
posted @ 2023-02-13 08:21  岭南春  阅读(87)  评论(0)    收藏  举报