【问题标题】:How does MVC4 optimization allow partial view scripts?MVC4 优化如何允许部分视图脚本?
【发布时间】:2013-01-07 15:29:53
【问题描述】:

局部视图和 MVC 的一个问题是,如果您的可重用局部视图需要某些 javascript,则无法将其包含在页面底部的脚本部分中。除了性能问题之外,这意味着还没有像 jquery 这样必要的东西,你必须使用时髦的延迟执行任何 jquery 相关代码。

解决这个问题的方法是允许部分中的部分,这样部分可以注册它的脚本出现在布局的正确位置。

据说,MVC4 的优化/捆绑功能应该可以解决这个问题。但是,当我在部分中调用 @Scripts.Render 时,它会将它们包含在部分所在的任何位置。将脚本放在页面末尾并没有什么神奇的作用。

请看 Erik Porter 的评论: http://aspnet.uservoice.com/forums/41199-general-asp-net/suggestions/2351628-support-section-render-in-partialviews

我在其他一些地方看到有人说 MVC 4 解决了这个问题,但没有关于如何解决的例子。

如何在其他脚本之后在正文末尾包含部分所需的脚本,使用 MVC4 优化来解决问题?

【问题讨论】:

  • 脚本不属于局部视图。为您的脚本使用父视图。
  • @MatijaGrcic 即使您将脚本外部化,您仍然面临同样的挑战。我不想用一堆用于部分的引导代码使父视图混乱,然后对您重用该部分的每个“父”重复此操作。

标签: asp.net-mvc asp.net-mvc-4


【解决方案1】:

您可以做的一件事是创建一些 HtmlHelper 扩展方法,如下所示:

using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Optimization;

public static class ScriptBundleManager
{
    private const string Key = "__ScriptBundleManager__";

    /// <summary>
    /// Call this method from your partials and register your script bundle.
    /// </summary>
    public static void Register(this HtmlHelper htmlHelper, string scriptBundleName)
    {
        //using a HashSet to avoid duplicate scripts.
        HashSet<string> set = htmlHelper.ViewContext.HttpContext.Items[Key] as HashSet<string>;
        if (set == null)
        {
            set = new HashSet<string>();
            htmlHelper.ViewContext.HttpContext.Items[Key] = set;
        }

        if (!set.Contains(scriptBundleName))
            set.Add(scriptBundleName);
    }

    /// <summary>
    /// In the bottom of your HTML document, most likely in the Layout file call this method.
    /// </summary>
    public static IHtmlString RenderScripts(this HtmlHelper htmlHelper)
    {
        HashSet<string> set = htmlHelper.ViewContext.HttpContext.Items[Key] as HashSet<string>;
        if (set != null)
            return Scripts.Render(set.ToArray());
        return MvcHtmlString.Empty;
    }
}

从你的部分你会这样使用它:

@{Html.Register("~/bundles/script1.js");}

在你的布局文件中:

   ...
   @Html.RenderScripts()
</body>

由于您的部分在布局文件结束之前运行,所有脚本包都将被注册并安全地呈现。

【讨论】:

  • 您的意思是:@{Html.Register("~/bundles/script1.js");} 实际加载文件名或 @{Html.Register("~/bundles/scriptbundle");} 加载在 BundleConfig.cs 中设置的 Bundle,正如您的 ~/bundles... 符号所暗示的那样让我知道 -谢谢
猜你喜欢
  • 2014-02-06
  • 1970-01-01
  • 2012-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-09-30
  • 2015-06-29
  • 1970-01-01
相关资源
最近更新 更多