Javascript和MVC4部分视图加载了AJAX [英] Javascript and MVC4 partial views loaded with AJAX

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

问题描述

我有一个ASP.NET MVC 4视图,它通过JQuery AJAX调用动态地将两个嵌套的部分加载到< div> 元素中。每个部分都有一大堆自己的Javascript。为了使其全部工作,我目前在每个AJAX调用的成功中拥有所有Javascript。

  function LoadPartial(someImportantId){
$ .ajax({
url:'@ Url.Action(LoadThePartial)'+'?id ='+ someImportantId,
type:'POST',
async:false,
success:function(result){
$(#partialContainerDiv)。html(result);
/ /这里有一大堆的javascript
}
});
}

由于有两个部分,每个需要数百行JavaScript,主视图文件变得难以管理。我很想将所有这些脚本代码放在一个单独的.js文件中,但是我仍然足够新颖,我非常依赖Chrome的脚本调试工具,而且我无法弄清楚如何(如果)我可以得到这个脚本文件加载。我试过:








  • 将主脚本添加到主视图中。这不行。没有
    的部分的Javascript正确连接,这对于
    a同步级别是有意义的。





有没有办法我可以单独的Javascript文件为AJAX加载的部分,仍然能够调试部分在客户端?更重要的是,我将所有这些Javascript放在AJAX加载的部分视图中?

解决方案

功能包含在主页中;调用AJAX成功处理程序中的函数,在部分加载后执行脚本。


I have an ASP.NET MVC 4 view that dynamically loads two nested partials into <div> elements via JQuery AJAX calls. Each of the partials has a pretty big pile of Javascript of its own. To get it all working, I currently have all of the Javascript in the success of each AJAX call:

function LoadPartial(someImportantId) {
    $.ajax({
        url: '@Url.Action("LoadThePartial")' + '?id=' + someImportantId,
        type: 'POST',
        async: false,
        success: function (result) {
            $("#partialContainerDiv").html(result);
            //here there be great piles of javascript
        }
    });
}

Since there are two of these partials and each requires hundreds of lines of Javascript, the main view file is getting difficult to manage. I'd love to put all of this script code into a separate .js file, but I'm still new enough to Javascript that I rely heavily on Chrome's script debugging tools, and I'm having trouble figuring out how (and if) I can get this script file to load. I've tried:

  • Adding a script include to the main view. This doesn't work. None of the partial's Javascript attaches correctly, which makes sense on a synchronization level.

Is there any way that I can have a separate Javascript file for an AJAX loaded partial and still be able to debug the partial on the client? More importantly, where do I put all of this Javascript for AJAX loaded partial views?

解决方案

Wrap the scripts for your partial in a function included in the main page; call the function in the AJAX success handler, executing the scripts after your partials have loaded.

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

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