gpt4 book ai didi

asp.net-mvc - MVC4优化如何允许部分 View 脚本?

转载 作者:行者123 更新时间:2023-12-04 04:31:11 24 4
gpt4 key购买 nike

局部 View 和MVC的一个问题是,如果可重用的局部 View 需要某些javascript,则无法包含它并将其加载到脚本部分的页面底部。除了性能问题外,这还意味着诸如jquery之类的必需事物尚未出现,您必须对任何依赖于jquery的代码使用时髦的延迟执行。

解决此问题的方法是允许局部文件中的各个部分,以便局部文件可以注册其脚本以出现在Layout的正确位置。

据推测,MVC4的优化/捆绑功能可以解决此问题。但是,当我在局部中调用@ Scripts.Render时,无论局部在哪里,它都将包含它们。将脚本放在页面末尾并没有任何魔力。

这里看到埃里克·波特的评论:
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;
}
}

在您的局部 View 中,您可以像这样使用它:
@{Html.Register("~/bundles/script1.js");}

并在您的布局文件中:
   ...
@Html.RenderScripts()
</body>

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

关于asp.net-mvc - MVC4优化如何允许部分 View 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14491801/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com