c# - 如何在局部视图 MVC.Core 中使用 @section 脚本
问题描述
在 ASP.NET Core MVC 中,可以为页面定义一个脚本部分,如下所示:
@section scripts {
<script>
alert('hello');
</script>
}
如果布局包含:
@RenderSection("Scripts", required: false)
您的脚本将被渲染。这在每个示例中都派上用场,以保证脚本将在所有 javascript 包含(如 jQuery)之后呈现。
但是如何在局部视图中渲染脚本呢?
解决方案
这是一个解决方案:
在布局页面中:
@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 中导入您的类助手,以便您可以在所有视图中使用它。
推荐阅读
- javascript - 如何连接 MongoDb 模型
- python-3.x - 如何将敏感数据保留在日志之外?
- opencl - 如果程序有效,如何出现 OpenCL 错误代码 -44 CL_INVALID_PROGRAM?
- shell - 在 Linux shell 中将 LDAP 时间戳转换为不同的格式
- r - 如何根据 R 中另一个数据框中的列删除列数据框中的行?
- swift - 将@State var 作为参数传递的 Swing 不会更新视图
- android - Android:自定义资源位置中的翻译文件夹
- python - 如果值包含特定字符串,如何创建字典
- sql - 基于模式 sql oracle 创建列
- r - 如果在 R 中的重复项之一中存在 NA,则删除重复项