如何在部分视图MVC.Core中使用@section脚本 [英] How to use @section scripts in a partial view MVC.Core
本文介绍了如何在部分视图MVC.Core中使用@section脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在ASP.NET Core MVC中,可以为如下页面定义脚本节:
In ASP.NET Core MVC it is possible to define a script section for a page like this:
@section scripts {
<script>
alert('hello');
</script>
}
如果布局包含:
@RenderSection("Scripts", required: false)
您的脚本将被渲染。每个示例都派上用场,以确保脚本将在包括jQuery之类的所有JavaScript之后得到呈现。
your script(s) will be rendered. This come in handy per example to guarantee that the scripts will be rendered after all javascript includes like jQuery.
但是如何在局部视图中呈现脚本?
But how to render a script in a partial view?
推荐答案
这是一个解决方案:
在布局页面中:
@Html.PageScripts()
在部分中:
@using (Html.BeginScripts())
{
<script>
alert('hello');
</script>
}
以及MVC.core的帮助器类。
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<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中导入类帮助程序,以便可以在所有视图中使用它。
Tip: import you class helper in _ViewImports.cshtml so you can use it in all views.
这篇关于如何在部分视图MVC.Core中使用@section脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文