MVC4 partial view javascript bundling Issue

自作多情 提交于 2019-11-28 01:53:10

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.

Finally got this to work. I removed my javascript from my partial view and placed it in the parent view (which is not partial), in the script section.This scripts section was created automatically when creating the view with scaffolding (Create) and was placed at the end of the page. To get this to work I had to move it to the top of the page - before the call to render my partial.

ClientDependency solves exactly this problem and allows you to add script references to partial views that get rolled up and placed at the end of the page (or wherever you specify) for you. It also deals with bundling, versioning and minification page by page.

The overhead of ensuring the script reference is on the "parent" View rather than the partial doesn't really bother me, but Client Dependency could be helpful if you had loads of partials all requiring their own script and CSS.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!