MVC4 部分视图 javascript 捆绑问题 [英] MVC4 partial view javascript bundling Issue

查看:22
本文介绍了MVC4 部分视图 javascript 捆绑问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Visual Studio 11 开发一个项目 ASP.net 4, MVC4(RC).我正在尝试呈现呈现部分视图的 MVC4 Razor 视图.我的部分视图需要一些 javascript.在我的部分视图中,当我在脚本部分中包含我的 javascript 时,它似乎没有加载.

I am working on a project ASP.net 4, MVC4(RC) using visual studio 11. I am trying to render an MVC4 Razor view that renders a partial view. I have some javascript required for my partial view. On my partial view when I include my javascript inside the scripts section as follows it does not seem to load.

@section Scripts {
    <script type="text/javascript">
        $(function () {
            alert("test");
        });
    </script>
}

如果我删除脚本部分,它会失败,因为当文档就绪代码运行时,jquery 库(捆绑并呈现在我的 _Layout.cshtml 页面上)尚未加载.

If I remove the scripts section it fails as the jquery libraries (which are bundled and rendered on my _Layout.cshtml page) have not yet loaded when the document ready code runs.

<script type="text/javascript">
    $(function () {
        alert("test");
    });
</script>

_Layout页面代码加载jquery库

_Layout Page code to load jquery libraries

@Scripts.Render("~/bundles/jquery")
@RenderSection("scripts", required: false)

有没有人知道解决方案,或者我只是以错误的方式解决这个问题?它毁了我的头!!

Does anyone know of a solution for this, or am I simply going about it the wrong way? Its wrecking my head!!

推荐答案

不要将您的脚本包装在部分的 document.ready 中:

Don't wrap your script in a document.ready in the partial:

@section Scripts {
    <script type="text/javascript">
        alert("test");
    </script>
}

啊,不要把脚本放在部分中.Javascript 代码应该放在单独的 javascript 文件中.如果您想在加载部分时执行一些 javascript,您只需将此脚本外部化为一个可重用的函数/插件,您可以在加载部分后调用该函数/插件.

Ah, and don't put scripts in partials. Javascript code should be placed in separate javascript files. If you want to execute some javascript when a partial is loaded, you simply externalize this script into a reusable function/plugin that you call once your partial is loaded.

这篇关于MVC4 部分视图 javascript 捆绑问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆