gpt4 book ai didi

jquery - 如何在部分 View 中使用jquery asp.net mvc 4

转载 作者:行者123 更新时间:2023-12-01 04:09:56 25 4
gpt4 key购买 nike

我正在开发 MVC-3 Web 应用程序。现在我将其更改为mvc4并将jquery文件放在_Layout页面的末尾

<html>
<head>
</head>
<body>
@Html.Partial("_Menu")
@RenderBody()
@System.Web.Optimization.Scripts.Render("~/jquery")
</body>
</html>

我在部分 View “_Menu”中使用了一些jquery,在Mvc 3中这工作正常,因为我将jquery文件放在head标签中,但现在当我调用这个部分 View 时遇到问题

Uncaught ReferenceError: $ is not defined

我认为这个问题是由于 jquery 文件在页面末尾加载造成的。我想到的解决方案是在 head 标签上加载 jquery 文件,但我不想这样做。

建议我任何其他解决方案。我如何在部分 View 中使用jquery。

谢谢

最佳答案

您不能在部分 View 中使用“Section”,但您可以编写一个扩展来执行相同的操作:

   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.
var 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)
{
var set = htmlHelper.ViewContext.HttpContext.Items[Key] as HashSet<string>;

return set != null ? Scripts.RenderFormat("<script type=\"text/javascript\" src=\"{0}\"></script>", set.ToArray()) : MvcHtmlString.Empty;
}


}

然后在 _Layout 文件中,在脚本包结束后:

@Html.RenderScripts()

然后在部分 View 的顶部:

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

然后,所有需要的功能将在定义 jQuery 后加载。

但是:请注意Kendo js 文件需要在使用其控件/扩展之前加载...因此它们始终需要位于布局文件的顶部...这很奇怪,但这就是生活...

关于jquery - 如何在部分 View 中使用jquery asp.net mvc 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21928611/

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