9

部分视图和 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 优化来解决问题?

4

1 回答 1

3

您可以做的一件事是创建一些 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>

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

于 2013-04-23T02:59:51.577 回答