部分视图和 MVC 的一个问题是,如果您的可重用部分视图需要某些 JavaScript,则无法包含它并将其加载到页面底部的脚本部分。除了性能问题之外,这意味着像 jquery 这样必要的东西还不存在,你必须使用任何依赖 jquery 的代码的时髦的延迟执行。
此问题的解决方案是允许部分中的部分,以便部分可以注册其脚本以显示在布局的正确位置。
据说,MVC4 的优化/捆绑功能应该可以解决这个问题。但是,当我在部分中调用 @Scripts.Render 时,它会在部分所在的位置包含它们。将脚本放在页面末尾并没有任何魔法。
请参阅埃里克·波特的评论:http://aspnet.uservoice.com/forums/41199-general-asp-net/suggestions/2351628-support-section-render-in-partialviews http://aspnet.uservoice.com/forums/41199-general-asp-net/suggestions/2351628-support-section-render-in-partialviews
我在其他一些地方看到人们说 MVC 4 解决了这个问题,但没有关于如何解决的示例。
如何使用 MVC4 优化在正文末尾包含其他脚本之后的部分所需的脚本来解决问题?
您可以做的一件事是创建一些 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>
由于您的部分在布局文件结束之前运行,所有脚本包都将被注册并且它们将被安全地渲染。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)