Aar*_*nLS 9 asp.net-mvc asp.net-mvc-4
部分视图和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优化来解决问题,在主体末尾包含部分所需的脚本?
您可以做的一件事是创建一些 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;
}
}
Run Code Online (Sandbox Code Playgroud)
从你的部分中,你可以像这样使用它:
@{Html.Register("~/bundles/script1.js");}
Run Code Online (Sandbox Code Playgroud)
在你的布局文件中:
...
@Html.RenderScripts()
</body>
Run Code Online (Sandbox Code Playgroud)
由于您的部分在布局文件结束之前运行,所有脚本包都将被注册并且它们将被安全地渲染。
| 归档时间: |
|
| 查看次数: |
1893 次 |
| 最近记录: |