7

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:

No script in debugger

  • 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.

Stuff does not work

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?

Community
  • 1
  • 1
AJ.
  • 16,368
  • 20
  • 95
  • 150

2 Answers2

7

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.

Evan Davis
  • 35,493
  • 6
  • 50
  • 57
  • Is there a way I can put the functions in a separate script file? – AJ. Dec 26 '12 at 17:22
  • Yes; essentially you'd wrap your entire _DiagnosticAssessment.js_ file in a named function, then call that function by name to _execute_ the code once ready. – Evan Davis Dec 26 '12 at 17:41
  • 1
    Unfortunately, I have a lot of razor syntax calls (like `@Url.Action()`) in my Javascript. Fortunately, I think I can remedy that with help from http://stackoverflow.com/q/4624626/27457. Thanks! – AJ. Dec 26 '12 at 20:05
1

There's now a solution that puts your dynamic JS code into the Sources treeview in the major browsers, which is all that is needed to make it debuggable. Add:

//# sourceURL=YOUR_FILENAME_OR_FULL_PATH_HERE

anywhere inside your <script> tag in your dynamically-loaded partial view. In my experiments, the space after the # seems to be required in Chrome and not in Firefox, which basically means it's required.

Source: https://developers.google.com/web/updates/2013/06/sourceMappingURL-and-sourceURL-syntax-changed and several other Stack Overflow questions

Kevin
  • 5,874
  • 3
  • 28
  • 35