从局部填充剃刀区


102

我尝试执行此操作的主要动机是,仅在页面底部将部分代码与其余Javascript一起使用,而不是在呈现部分代码的页面中间,获取Javascript。

这是我要执行的操作的简化示例:

这是在正文之前的“脚本”部分的布局。

<!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />    
</head>

<body>
    @RenderBody()
    <script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
    @RenderSection("Scripts", false)
</body>
</html>

这是使用此布局的示例视图。

<h2>This is the view</h2>

@{Html.RenderPartial("_Partial");}

@section Scripts {
<script type="text/javascript">
        alert("I'm a view.");
</script>
}

这是从视图渲染的部分图像。

<p>This is the partial.</p>

@* this never makes it into the rendered page *@
@section Scripts {
<script type="text/javascript">
    alert("I'm a partial."); 
</script>
}

在此示例中,视图中指定的标记被放置到该部分中,而部分标记则没有。是否可以使用Razor从局部视图填充剖面?如果不是,那么还有什么其他方法来获取Javascript,而这些Javascript只需要页面底部的局部对象而不全局包含它?


可能是一个问题,因为您在部分
.IDK中

不是。即使该部分不在视图中,该部分中的代码也不会使其进入最终呈现的页面。我认为SLaks是正确的,因为局部对象不能参与父视图的部分。
克雷格(Craig M)

Answers:


78

我处理这个问题的方法是为HtmlHelper类编写几个扩展方法。这样,局部视图就可以说它们需要脚本,然后在布局视图中将我调用的标签写入我的辅助方法,以发出所需的脚本。

以下是辅助方法:

public static string RequireScript(this HtmlHelper html, string path, int priority = 1)
{
    var requiredScripts = HttpContext.Current.Items["RequiredScripts"] as List<ResourceInclude>;
    if (requiredScripts == null) HttpContext.Current.Items["RequiredScripts"] = requiredScripts = new List<ResourceInclude>();
    if (!requiredScripts.Any(i => i.Path == path)) requiredScripts.Add(new ResourceInclude() { Path = path, Priority = priority });
    return null;
}

public static HtmlString EmitRequiredScripts(this HtmlHelper html)
{
    var requiredScripts = HttpContext.Current.Items["RequiredScripts"] as List<ResourceInclude>;
    if (requiredScripts == null) return null;
    StringBuilder sb = new StringBuilder();
    foreach (var item in requiredScripts.OrderByDescending(i => i.Priority))
    {
        sb.AppendFormat("<script src=\"{0}\" type=\"text/javascript\"></script>\n", item.Path);
    }
    return new HtmlString(sb.ToString());
}
public class ResourceInclude
{
    public string Path { get; set; }
    public int Priority { get; set; }
}

设置好位置后,只需要调用即可@Html.RequireScript("/Path/To/Script")

然后在布局视图的头部 @Html.EmitRequiredScripts()

另外一个好处是,它允许您清除重复的脚本请求。如果您有多个需要给定脚本的视图/局部视图,则可以放心地假设您只会输出一次


优雅而干净的解决方案。+1
bevacqua

只是在拉出我的大部分头发后才遇到此解决方案-出色的解决方案....
higgsy 2012年

我无法使用此解决方案。似乎在任何局部视图调用RequireScript()之前先调用EmitRequiredScripts()。难道我做错了什么?
布莱恩·罗斯

听起来有些不对劲,Bryan。在过去一年左右的时间里,我已经广泛使用了该解决方案,并且效果很好。也许用您的问题的详细信息发布一个新问题并在此处链接url
贝尔先生2012年

1
部署新版本的应用程序时,它是否有任何缓存清除支持?开箱即用的@ scripts.Render()方法将在构建时生成的末尾粘贴一个URL参数,以便在部署新版本时强制浏览器获取最新版本。
西蒙·格林

28

部分视图不能参与其父视图的部分。


1
这就是我所怀疑的。谢谢。
克雷格M

@JohnBubriski Razor 2中有。版本。
Shimmy Weitzhandler,2012年

@SLaks,为什么这是设计使然?在我的场景中,我有一个局部部分,它是横幅旋转器,我希望它的脚本/样式仅在打开时才加载,为什么以内联方式加载它不好?
Shimmy Weitzhandler,2012年

2
@Shimmy:您应该使用资源管理系统,例如Cassette。
SLaks 2012年

谢谢。我会调查一下。
Shimmy Weitzhandler,2012年

13

您可能还有第二部分,仅负责注入必要的JavaScript。@if如果需要,在块周围放置几个脚本:

@model string
@if(Model == "bla") {
    <script type="text/javascript">...</script>
}

@else if(Model == "bli") {
    <script type="text/javascript">...</script>
}

显然可以清除一点,但是在Scripts您的视图部分中:

@section Scripts
{
    @Html.Partial("_Scripts", "ScriptName_For_Partial1")
}

同样,它可能不会赢得美容大奖,但是会起作用。


1
这与我最终完成的工作非常接近。绝对不是很漂亮,但是可以。唯一的缺点是您无法通过ajax调用获得局部代码,并且无法包含JS。我认为从长远来看,我将最终使用jQuery模板进行重构,仅从控制器发送JSON,而不是在服务器端构建html。
Craig M

@CraigM也是我要去的地方。MVC是合法的,但对我而言,使用客户端模板(我正在研究Backbone.js)并从API进行推/拉对我来说意义更大。
one.beat.consumer 2012年

@ one.beat.customer-因为我也使用Backbone,所以我一直在使用下划线的模板,但是我正在考虑从Twitter切换到Hogan库,或者从Nodejitsu切换到Plates。两者都有相当不错的功能。
Craig M

10

执行此操作的更优雅的方法是将部分视图脚本移到单独的文件中,然后在视图的“脚本”部分中呈现它:

<h2>This is the view</h2>

@Html.RenderPartial("_Partial")

@section Scripts
{
    @Html.RenderPartial("_PartialScripts")

    <script type="text/javascript">
        alert("I'm a view script.");
    </script>
}

局部视图_ Partial.cshtml

<p>This is the partial.</p>

局部视图_ PartialScripts.cshtml仅包含脚本:

<script type="text/javascript">
    alert("I'm a partial script!");
</script>

它不像其他答案中建议的某些扩展方法或插件那样自动,但是确实具有简单明了的优点。喜欢它。
Mark Meuer 2014年

7

安装Forloop.HtmlHelpers nuget软件包-它添加了一些用于在局部视图和编辑器模板中管理脚本的助手。

在布局中的某处,您需要致电

@Html.RenderScripts()

这将是在页面中输出任何脚本文件和脚本块的位置,因此我建议将其放在布局中的主要脚本之后和脚本部分之后(如果有的话)。

如果您将Web优化框架与捆绑在一起使用,则可以使用重载

@Html.RenderScripts(Scripts.Render)

因此,此方法用于写出脚本文件。

现在,只要您想在视图,局部视图或模板中添加脚本文件或块,只需使用

@using (Html.BeginScriptContext())
{
  Html.AddScriptFile("~/Scripts/jquery.validate.js");
  Html.AddScriptBlock(
    @<script type="text/javascript">
       $(function() { $('#someField').datepicker(); });
     </script>
  );
}

帮助程序确保多次添加时仅呈现一个脚本文件引用,并且还确保按预期顺序呈现脚本文件,即

  1. 布局
  2. 局部和模板(按在视图中显示的顺序,从上到下)

5

[更新的版本] @Necrocubus问题之后的更新版本,以包含嵌入式脚本。

public static class ScriptsExtensions
{
    const string REQ_SCRIPT = "RequiredScript";
    const string REQ_INLINESCRIPT = "RequiredInlineScript";
    const string REQ_STYLE = "RequiredStyle";

    #region Scripts
    /// <summary>
    /// Adds a script 
    /// </summary>
    /// <param name="html"></param>
    /// <param name="path"></param>
    /// <param name="priority">Ordered by decreasing priority </param>
    /// <param name="bottom"></param>
    /// <param name="options"></param>
    /// <returns></returns>
    public static string RequireScript(this IHtmlHelper html, string path, int priority = 1, bool bottom=false, params string[] options)
    {
        var ctxt = html.ViewContext.HttpContext;

        var requiredScripts = ctxt.Items[REQ_SCRIPT] as List<ResourceToInclude>;
        if (requiredScripts == null) ctxt.Items[REQ_SCRIPT] = requiredScripts = new List<ResourceToInclude>();
        if (!requiredScripts.Any(i => i.Path == path)) requiredScripts.Add(new ResourceToInclude() { Path = path, Priority = priority, Options = options, Type=ResourceType.Script, Bottom=bottom});
        return null;
    }

    /// <summary>
    /// 
    /// </summary>
    /// <param name="html"></param>
    /// <param name="script"></param>
    /// <param name="priority">Ordered by decreasing priority </param>
    /// <param name="bottom"></param>
    /// <returns></returns>
    public static string RequireInlineScript(this IHtmlHelper html, string script, int priority = 1, bool bottom = false)
    {
        var ctxt = html.ViewContext.HttpContext;

        var requiredScripts = ctxt.Items[REQ_INLINESCRIPT] as List<InlineResource>;
        if (requiredScripts == null) ctxt.Items[REQ_INLINESCRIPT] = requiredScripts = new List<InlineResource>();
        requiredScripts.Add(new InlineResource() { Content=script, Priority = priority, Bottom=bottom, Type=ResourceType.Script});
        return null;
    }

    /// <summary>
    /// Just call @Html.EmitRequiredScripts(false)
    /// at the end of your head tag and 
    /// @Html.EmitRequiredScripts(true) at the end of the body if some scripts are set to be at the bottom.
    /// </summary>
    public static HtmlString EmitRequiredScripts(this IHtmlHelper html, bool bottom)
    {
        var ctxt = html.ViewContext.HttpContext;

        var requiredScripts = ctxt.Items[REQ_SCRIPT] as List<ResourceToInclude>;
        var requiredInlineScripts = ctxt.Items[REQ_INLINESCRIPT] as List<InlineResource>;
        var scripts = new List<Resource>();
        scripts.AddRange(requiredScripts ?? new List<ResourceToInclude>());
        scripts.AddRange(requiredInlineScripts ?? new List<InlineResource>());
        if (scripts.Count==0) return null;
        StringBuilder sb = new StringBuilder();
        foreach (var item in scripts.Where(s=>s.Bottom==bottom).OrderByDescending(i => i.Priority))
        {
            sb.Append(item.ToString());
        }
        return new HtmlString(sb.ToString());
    }
    #endregion Scripts

    #region Styles
    /// <summary>
    /// 
    /// </summary>
    /// <param name="html"></param>
    /// <param name="path"></param>
    /// <param name="priority">Ordered by decreasing priority </param>
    /// <param name="options"></param>
    /// <returns></returns>
    public static string RequireStyle(this IHtmlHelper html, string path, int priority = 1, params string[] options)
    {
        var ctxt = html.ViewContext.HttpContext;

        var requiredScripts = ctxt.Items[REQ_STYLE] as List<ResourceToInclude>;
        if (requiredScripts == null) ctxt.Items[REQ_STYLE] = requiredScripts = new List<ResourceToInclude>();
        if (!requiredScripts.Any(i => i.Path == path)) requiredScripts.Add(new ResourceToInclude() { Path = path, Priority = priority, Options = options });
        return null;
    }

    /// <summary>
    /// Just call @Html.EmitRequiredStyles()
    /// at the end of your head tag
    /// </summary>
    public static HtmlString EmitRequiredStyles(this IHtmlHelper html)
    {
        var ctxt = html.ViewContext.HttpContext;

        var requiredScripts = ctxt.Items[REQ_STYLE] as List<ResourceToInclude>;
        if (requiredScripts == null) return null;
        StringBuilder sb = new StringBuilder();
        foreach (var item in requiredScripts.OrderByDescending(i => i.Priority))
        {
            sb.Append(item.ToString());
        }
        return new HtmlString(sb.ToString());
    }
    #endregion Styles

    #region Models
    public class InlineResource : Resource
    {
        public string Content { get; set; }
        public override string ToString()
        {
            return "<script>"+Content+"</script>";
        }
    }

    public class ResourceToInclude : Resource
    {
        public string Path { get; set; }
        public string[] Options { get; set; }
        public override string ToString()
        {
            switch(Type)
            {
                case ResourceType.CSS:
                    if (Options == null || Options.Length == 0)
                        return String.Format("<link rel=\"stylesheet\" href=\"{0}\" type=\"text/css\" />\n", Path);
                    else
                        return String.Format("<link rel=\"stylesheet\" href=\"{0}\" type=\"text/css\" {1} />\n", Path, String.Join(" ", Options));
                default:
                case ResourceType.Script:
                    if (Options == null || Options.Length == 0)
                        return String.Format("<script src=\"{0}\" type=\"text/javascript\"></script>\n", Path);
                    else
                        return String.Format("<script src=\"{0}\" type=\"text/javascript\" {1}></script>\n", Path, String.Join(" ", Options));
            }
        }
    }
    public class Resource
    {
        public ResourceType Type { get; set; }
        public int Priority { get; set; }
        public bool Bottom { get; set; }
    }
    public enum ResourceType
    {
        Script,
        CSS
    }
    #endregion Models
}

我的2美分是一个旧帖子,但仍然有用,因此这里是Bell先生与ASP.Net Core配合使用的解决方案的升级更新。

它允许从导入的局部视图和子视图向主布局添加脚本和样式,并可以向脚本/样式导入添加选项(例如异步延迟等):

public static class ScriptsExtensions
{
    const string REQ_SCRIPT = "RequiredScript";
    const string REQ_STYLE = "RequiredStyle";

    public static string RequireScript(this IHtmlHelper html, string path, int priority = 1, params string[] options)
    {
        var ctxt = html.ViewContext.HttpContext;

        var requiredScripts = ctxt.Items[REQ_SCRIPT] as List<ResourceInclude>;
        if (requiredScripts == null) ctxt.Items[REQ_SCRIPT] = requiredScripts = new List<ResourceInclude>();
        if (!requiredScripts.Any(i => i.Path == path)) requiredScripts.Add(new ResourceInclude() { Path = path, Priority = priority, Options = options });
        return null;
    }


    public static HtmlString EmitRequiredScripts(this IHtmlHelper html)
    {
        var ctxt = html.ViewContext.HttpContext;

        var requiredScripts = ctxt.Items[REQ_SCRIPT] as List<ResourceInclude>;
        if (requiredScripts == null) return null;
        StringBuilder sb = new StringBuilder();
        foreach (var item in requiredScripts.OrderByDescending(i => i.Priority))
        {
            if (item.Options == null || item.Options.Length == 0)
                sb.AppendFormat("<script src=\"{0}\" type=\"text/javascript\"></script>\n", item.Path);
            else
                sb.AppendFormat("<script src=\"{0}\" type=\"text/javascript\" {1}></script>\n", item.Path, String.Join(" ", item.Options));

        }
        return new HtmlString(sb.ToString());
    }


    public static string RequireStyle(this IHtmlHelper html, string path, int priority = 1, params string[] options)
    {
        var ctxt = html.ViewContext.HttpContext;

        var requiredScripts = ctxt.Items[REQ_STYLE] as List<ResourceInclude>;
        if (requiredScripts == null) ctxt.Items[REQ_STYLE] = requiredScripts = new List<ResourceInclude>();
        if (!requiredScripts.Any(i => i.Path == path)) requiredScripts.Add(new ResourceInclude() { Path = path, Priority = priority, Options = options });
        return null;
    }


    public static HtmlString EmitRequiredStyles(this IHtmlHelper html)
    {
        var ctxt = html.ViewContext.HttpContext;

        var requiredScripts = ctxt.Items[REQ_STYLE] as List<ResourceInclude>;
        if (requiredScripts == null) return null;
        StringBuilder sb = new StringBuilder();
        foreach (var item in requiredScripts.OrderByDescending(i => i.Priority))
        {
            if (item.Options == null || item.Options.Length == 0)
                sb.AppendFormat("<link rel=\"stylesheet\" href=\"{0}\" type=\"text/css\" />\n", item.Path);
            else
                sb.AppendFormat("<link rel=\"stylesheet\" href=\"{0}\" type=\"text/css\" {1} />\n", item.Path, String.Join(" ", item.Options));
        }
        return new HtmlString(sb.ToString());
    }


    public class ResourceInclude
    {
        public string Path { get; set; }
        public int Priority { get; set; }
        public string[] Options { get; set; }
    }
}

谢谢你,兄弟!应该对此进行更多投票,因为它比6岁的答案更有意义。
Necroqubus

另外,是否可以修改这些扩展名以允许输入脚本的某些部分?@ <text> </ text>或类似部分的内容?否则,我仍然需要一个小的JS脚本来初始化带有服务器端模型变量的其他脚本:/
Necroqubus

@Necroqubus,您可以检查更新的版本,但是我尚未测试过:)
Jean Jean

好吧,我会尝试为您测试。我希望它可以与ASP.NET Core 1.0 MVC一起使用。对于上下文,我有多层嵌套的部分,并希望它们的脚本在页脚处呈现。
Necroqubus

不需要<text>,只需将其添加为字符串(如果愿意,您仍可以在多行中添加@“”作为前缀),并且没有<script>标签
Jean

1

您可以创建一个新Layout页面,并将PartialView包裹在全视图中,该全视图负责呈现内容以及所有库部分。

例如,假设我有以下代码:

HomeController.cs

[HttpGet]
public ActionResult About()
{
    var vm = new AboutViewModel();
    return View("About", vm);
}

呈现“整页”视图时,通常是通过合并两个文件来呈现的:

About.cshtml

@model AboutViewModel

@{
    ViewBag.Title = "About CSHN";
}

<h3>@ViewBag.Title</h3>

@section Styles {
    <style> /* style info here */ </style>
}

@section Scripts {
    <script> /* script info here */ </script>
}

_Layout.cshtml (或在_ViewStart中指定或在页面中覆盖的任何内容)

<!DOCTYPE html>

<html>
<head>
    @RenderSection("Styles", false)
    <title>@ViewBag.Title</title>
</head>
<body>
    @RenderBody()

    @RenderSection("scripts", false)
</body>
</html>

现在,假设您要渲染About.cshtml部分视图,或者作为响应AJAX调用的模式窗口。这里的目标是仅返回About页面,脚本和所有内容中指定的内容,而不包含_Layout.cshtml主版式中的所有内容(例如完整内容)<html>文档)。

您可以像这样尝试,但是它不会附带任何节块:

return PartialView("About", vm);

而是添加一个更简单的布局页面,如下所示:

_PartialLayout.cshtml

<div>
    @RenderBody()
    @RenderSection("Styles", false)
    @RenderSection("scripts", false)
</div>

或者支持这样的模式窗口:

_ModalLayout.cshtml

<div class="modal modal-page fade" tabindex="-1" role="dialog" >
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">

            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
                <h4 class="modal-title">@ViewBag.Title</h4>
            </div>

            <div class="modal-body">

                @RenderBody()
                @RenderSection("Styles", false)
                @RenderSection("scripts", false)

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-inverse" data-dismiss="modal">Dismiss</button>
            </div>
        </div>
    </div>
</div>

然后,您可以在此控制器或要同时呈现视图内容和脚本的任何其他处理程序中指定自定义主视图

[HttpGet]
public ActionResult About()
{
    var vm = new AboutViewModel();
    return !Request.IsAjaxRequest()
              ? View("About", vm)
              : View("About", "~/Views/Shared/_ModalLayout.cshtml", vm);
}

1

对于那些寻求aspnet core 2.0版本的用户:

    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using Microsoft.AspNetCore.Html;
    using Microsoft.AspNetCore.Http;

    public static class HttpContextAccessorExtensions
    {
        public static string RequireScript(this IHttpContextAccessor htmlContextAccessor, string path, int priority = 1)
        {
            var requiredScripts = htmlContextAccessor.HttpContext.Items["RequiredScripts"] as List<ResourceInclude>;
            if (requiredScripts == null) htmlContextAccessor.HttpContext.Items["RequiredScripts"] = requiredScripts = new List<ResourceInclude>();
            if (requiredScripts.All(i => i.Path != path)) requiredScripts.Add(new ResourceInclude() { Path = path, Priority = priority });
            return null;
        }

        public static HtmlString EmitRequiredScripts(this IHttpContextAccessor htmlContextAccessor)
        {
            var requiredScripts = htmlContextAccessor.HttpContext.Items["RequiredScripts"] as List<ResourceInclude>;
            if (requiredScripts == null) return null;
            StringBuilder sb = new StringBuilder();
            foreach (var item in requiredScripts.OrderByDescending(i => i.Priority))
            {
                sb.AppendFormat("<script src=\"{0}\" type=\"text/javascript\"></script>\n", item.Path);
            }
            return new HtmlString(sb.ToString());
        }
        public class ResourceInclude
        {
            public string Path { get; set; }
            public int Priority { get; set; }
        }
    }

在脚本渲染部分调用之后添加到布局中:

@HttpContextAccessor.EmitRequiredScripts()

在您的局部视图中:

@inject IHttpContextAccessor HttpContextAccessor

...

@HttpContextAccessor.RequireScript("/scripts/moment.min.js")

0

根据上面的Bell And Shimmy先生的回答,我为Bundle脚本添加了额外的功能。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Web.Mvc;
namespace ABC.Utility
{
public static  class PartialViewHelper
{
    public static string RequireScript(this HtmlHelper html, string path, int priority = 1)
    {
        var requiredScripts = HttpContext.Current.Items["RequiredScripts"] as List<ResourceInclude>;
        if (requiredScripts == null) HttpContext.Current.Items["RequiredScripts"] = requiredScripts = new List<ResourceInclude>();
        if (!requiredScripts.Any(i => i.Path == path)) requiredScripts.Add(new ResourceInclude() { Path = path, Priority = priority });
        return null;
    }

    public static string RequireBundleStyles(this HtmlHelper html, string bundleName)
    {
        var a = System.Web.Optimization.Styles.Render(bundleName);
        var requiredStyles = HttpContext.Current.Items["RequiredStyles"] as IHtmlString;
        if (requiredStyles == null) HttpContext.Current.Items["RequiredStyles"] = requiredStyles = a;
        return null;
    }

    public static string RequireBundleScripts(this HtmlHelper html, string bundleName)
    {
        var a=System.Web.Optimization.Scripts.Render(bundleName);
        var requiredScripts = HttpContext.Current.Items["RequiredScripts"] as IHtmlString;
        if (requiredScripts == null) HttpContext.Current.Items["RequiredScripts"] = requiredScripts = a;
        return null;
    }

    public static HtmlString EmitRequiredBundleStyles(this HtmlHelper html)
    {
        var requiredStyles = HttpContext.Current.Items["RequiredStyles"] as IHtmlString;
        if (requiredStyles == null) return null;
        return MvcHtmlString.Create(requiredStyles.ToHtmlString()) ;
    }

    public static HtmlString EmitRequiredBundleScripts(this HtmlHelper html)
    {
        var requiredScripts = HttpContext.Current.Items["RequiredScripts"] as IHtmlString;
        if (requiredScripts == null) return null;
        return MvcHtmlString.Create(requiredScripts.ToHtmlString());
    }

    public static HtmlString EmitRequiredScripts(this HtmlHelper html)
    {
        var requiredScripts = HttpContext.Current.Items["RequiredScripts"] as List<ResourceInclude>;
        if (requiredScripts == null) return null;
        StringBuilder sb = new StringBuilder();
        foreach (var item in requiredScripts.OrderByDescending(i => i.Priority))
        {
            sb.AppendFormat("<script src=\"{0}\" type=\"text/javascript\"></script>\n", item.Path);
        }
        return new HtmlString(sb.ToString());
    }
    public class ResourceInclude
    {
        public string Path { get; set; }
        public int Priority { get; set; }
    }
}//end class
}// end namespace  

在PartialView上的示例:-@ Html.RequireBundleStyles(“〜/ bundles / fileupload / bootstrap / BasicPlusUI / css”); @ Html.RequireBundleScripts(“〜/ bundles / fileupload / bootstrap / BasicPlusUI / js”);

MasterPage上的示例:-@ Html.EmitRequiredBundleStyles()



0

ClientDependency.Core.Mvc.dll中也实现了此功能。它提供了html帮助器:@ Html.RequiresJs和@ Html.RenderJsHere()。Nuget包:ClientDependency-Mvc


0

这是我对常见问题“如何将部分视图从asp.net mvc的主视图或主布局视图注入的解决方案”的解决方案。如果使用关键字“ section + partial”在stackoverflow上进行搜索,您将获得大量相关问题和给出的答案,但是通过剃刀引擎语法,这些问题对我而言似乎都不是很优雅。因此,我只看一下Razor引擎,看看是否可以找到更好的解决方案。

幸运的是,我发现Razor引擎如何为视图模板文件(* .cshtml,*。vbhtml)进行编译对我来说很有趣。(我将在后面解释),下面是我的解决方案代码,我认为使用起来非常简单,优雅。

namespace System.Web.Mvc.Html
{
    public static class HtmlHelperExtensions
    {
        /// <summary>
        /// 确保所有视图,包括分部视图(PartialView)中的节(Section)定义被按照先后顺序追加到最终文档输出流中
        /// </summary>
        public static MvcHtmlString EnsureSection(this HtmlHelper helper)
        {
            var wp = (WebViewPage)helper.ViewDataContainer;
            Dictionary<string, WebPages.SectionWriter> sw = (Dictionary<string, WebPages.SectionWriter>)typeof(WebPages.WebPageBase).GetProperty("SectionWriters", Reflection.BindingFlags.NonPublic | Reflection.BindingFlags.Instance).GetValue(wp);
            if (!helper.ViewContext.HttpContext.Items.Contains("SectionWriter"))
            {
                Dictionary<string, Stack<WebPages.SectionWriter>> qss = new Dictionary<string, Stack<WebPages.SectionWriter>>();
                helper.ViewContext.HttpContext.Items["SectionWriter"] = qss;
            }
            var eqs = (Dictionary<string, Stack<WebPages.SectionWriter>>)helper.ViewContext.HttpContext.Items["SectionWriter"];
            foreach (var kp in sw)
            {
                if (!eqs.ContainsKey(kp.Key)) eqs[kp.Key] = new Stack<WebPages.SectionWriter>();
                eqs[kp.Key].Push(kp.Value);
            }
            return MvcHtmlString.Create("");
        }

        /// <summary>
        /// 在文档流中渲染指定的节(Section)
        /// </summary>
        public static MvcHtmlString RenderSectionEx(this HtmlHelper helper, string section, bool required = false)
        {
            if (helper.ViewContext.HttpContext.Items.Contains("SectionWriter"))
            {
                Dictionary<string, Stack<WebPages.SectionWriter>> qss = (Dictionary<string, Stack<WebPages.SectionWriter>>)helper.ViewContext.HttpContext.Items["SectionWriter"];
                if (qss.ContainsKey(section))
                {
                    var wp = (WebViewPage)helper.ViewDataContainer;
                    var qs = qss[section];
                    while (qs.Count > 0)
                    {
                        var sw = qs.Pop();
                        var os = ((WebViewPage)sw.Target).OutputStack;
                        if (os.Count == 0) os.Push(wp.Output);
                        sw.Invoke();
                    }
                }
                else if (!qss.ContainsKey(section) && required)
                {
                    throw new Exception(string.Format("'{0}' section is not defined.", section));
                }
            }
            return MvcHtmlString.Create("");
        }
    }
}

用法:使用代码也非常简单,并且看起来与通常的样式几乎相同。它还支持嵌套部分视图的任何级别。即。我有一个视图模板链:_ViewStart.cshtml-> layout.cshtml-> index.cshtml-> [head.cshtml,foot.cshtml]-> ad.cshtml。

在layout.cshtml中,我们有:

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>@ViewBag.Title - @ViewBag.WebSetting.Site.WebName</title>
    <base href="@ViewBag.Template/" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1.0, user-scalable=0,user-scalable=no">
    <meta name="format-detection" content="telephone=no">
    <meta name="renderer" content="webkit">
    <meta name="author" content="Taro Technology Co.,LTD" />
    <meta name="robots" content="index,follow" />
    <meta name="description" content="" />
    <meta name="keywords" content="" />
    <link rel="alternate icon" type="@ViewBag.WebSetting.Site.WebFavIcon" href="@ViewBag.WebSetting.Site.WebFavIcon">
    @Html.RenderSectionEx("Head")
</head>
<body>
    @RenderBody()
    @Html.RenderSectionEx("Foot")
</body>
</html>

在index.cshtml中,我们有:

@{
    ViewBag.Title = "首页";
}

@Html.Partial("head")
<div class="am-container-1">
    .......
</div>
@Html.Partial("foot")

在head.cshtml中,我们将获得以下代码:

@section Head{
    <link rel="stylesheet" href="assets/css/amazeui.css" />
    <link rel="stylesheet" href="assets/css/style.css" />
}

<header class="header">
   ......
</header>
@Html.EnsureSection()

在foot.cshtml或ad.cshtml中是相同的,您仍然可以在其中定义Head或Foot部分,请确保在部分视图文件的末尾调用一次@ Html.EnsureSection()。这是您摆脱ASP MVC中的问题所需要做的所有事情。

我只是分享我的代码段,以便其他人可以使用它。如果您觉得这很有用,请随时为我的帖子打分。:)

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.