Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
572 views
in Technique[技术] by (71.8m points)

asp.net mvc 4 - MVC4 partial view javascript bundling Issue

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>
}

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 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!!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...