ASP.NET MVC2 AJAX: Executing Dynamically Loaded JavaScript

   Submit to Reddit      
  

(or ASP.NET MVC2 AJAX: ASP.NET MVC2 Client Validation in an AJAX Loaded Partial View)

I have been tinkering with ASP.NET MVC2 for a while and I had the problem where the MVC2 Client Validation did not work when I was dynamically loading a partial view through MVC2 AJAX. Upon further investigation, I discovered that the issue was not limited just to MVC2 Client Validation, but to all JavaScript that is dynamically loaded through MVC2 AJAX. The issue has to do with the way that the response is injected into the DOM element - through the InnerHTML property. Any script block injected into that property will not be executed.

Note: when I refer to the ASP.NET MVC2 AJAX, I am specifically referring to the usage of method calls such as Ajax.ActionLink() and Ajax.BeginForm().

There are many blogs and tutorials that discuss how to load partial views asynchronously with AJAX in ASP.NET MVC2, and there are even more articles on how do that with jQuery. Unfortunately most of these deal with the simplistic scenario of explaining the basics of partial views.

It is difficult to find any information on how to do MVC2 Client Validation (or use any JavaScript) from within a partial view that is loaded dynamically with ASP.NET MVC2 AJAX. There are however a number of forum posts with people questioning exactly how to do this!

Now, I am not going to discuss how it might be better practice to put all the JavaScript in separate .js files and load those when the page is initially loaded. While I agree, there are times when that is simply not an option... MVC2 Client Validation is one such example, as it emits JavaScript when the partial view is rendered.

Side note: I originally came across this same type of behaviour is ASP.NET Web Forms in 2007, with the AjaxControlToolkit UpdatePanel. A workable solution for ASP.NET Web Forms is described here: http://weblogs.asp.net/infinitiesloop/archive/2007/09/17/inline-script-inside-an-asp-net-ajax-updatepanel.aspx.

Below are some links to various posts by other people who have had similar issues.

In summary, the responses essentially say three things:

  1. ASP.NET MVC AJAX will not execute JavaScript that is dynamically loaded into a DOM element;

  2. The only workable solution is to not use MVC AJAX and instead write JavaScript and use jQuery to do all the AJAX; and

  3. ASP.NET MVC2 Client Validation needs to be reinitialised after a partial view is dynamically loaded and the JavaScript is executed.

I found these responses to be unsatisfactory! Are people seriously suggesting that one does all of that in the AjaxOption.OnSuccess delegate every time? Right now, I want to take advantage of MVC2 Client Validation and I want to use MVC AJAX - because it is simpler than the alternatives. It should 'just work', shouldn't it? Am I asking too much? After all, this is the second version of ASP.NET MVC!

So noting that JavaScript is a dynamic language, I created the following solution which seamlessly extends the ASP.NET MVC2 JavaScript to make the execution of dynamically loaded JavaScript and the reinitialisation of MVC2 Client Validation happen automatically.

Without diving deeply into the code, the approach is to override the MicrosoftMvcAjax.js Sys.Mvc.MvcHelpers._onComplete method so that I can then hook into the ajaxOptions.onSuccess delegate in order to use jQuery.globalEval() to execute the JavaScript dynamically loaded into the target element, and then finally reinitialise the MVC2 Client Validation.

Just by including this script in an application (carefully loaded AFTER the jQuery and MicrosoftMVCValidation scripts!), this will now happen seamlessly on every MVC2 AJAX request.

Yay! Now the dynamically loaded JavaScript executes, and the MVC2 Client Validation works on partial views that are loaded dynamically with MVC AJAX!

AjaxLoadedContentScriptFix.js

////////////////////////////////////////////////////////////////////////////////
//
// Sys.Mvc.MvcHelpers.AjaxLoadedContentScriptFix
//
// Original Author: Adam M Craven (https://devblog.channeladam.com)
//
// This extension to ASP.NET MVC2 makes any script loaded as part of dynamically loaded content
// be executable and reinitialises the MVC2 client validation to enable that processing to occur
// for an AJAX loaded view.
//
// Warning: This script may not work with future versions of the minimised MicrosoftMvcAjax.js.
//
// When content (e.g. Partial Views) is dynamically loaded into a DOM target element through AJAX
// via the standard ASP.NET MVC2 "Ajax.ActionLink()" or "Ajax.BeginForm()" methods, any script
// (such as javascript or MVC client validation script) that was emitted is not executed because
// the content is assigned to the target element's "innerHTML" property. This will not cause the
// script to be executed or execuatable.
//
// Must be included after jQuery and the MicrosoftMvcValidation javascript, typically like this:
//    <script type="text/javascript" src="<%=Url.Content("~/Scripts/jquery-1.4.1.min.js") %>"></script>
//    <script type="text/javascript" src="<%=Url.Content("~/Scripts/MicrosoftAjax.js") %>"></script>
//    <script type="text/javascript" src="<%=Url.Content("~/Scripts/MicrosoftMvcAjax.js") %>"></script>
//    <script type="text/javascript" src="<%=Url.Content("~/Scripts/MicrosoftMvcValidation.js") %>"></script>
//    <script type="text/javascript" src="<%=Url.Content("~/Scripts/AjaxLoadedContentScriptFix.js") %>"></script>
//

Sys.Mvc.MvcHelpers.AjaxLoadedContentScriptFix = function Sys_Mvc_MvcHelpers_AjaxLoadedContentScriptFix() {}

Sys.Mvc.MvcHelpers.AjaxLoadedContentScriptFix._onComplete = function Sys_Mvc_MvcHelpers_AjaxLoadedContentScriptFix$_onComplete(request, ajaxOptions, ajaxContext) {
    /// <param name="request" type="Sys.Net.WebRequest">
    /// </param>
    /// <param name="ajaxOptions" type="Sys.Mvc.AjaxOptions">
    /// </param>
    /// <param name="ajaxContext" type="Sys.Mvc.AjaxContext">
    /// </param>

    // Hook into the ajaxOptions.onSuccess delegate
    ajaxContext._ajaxLoadedContentScriptFixOrigAjaxOptionsOnSuccess = ajaxOptions.onSuccess;
    ajaxOptions.onSuccess = Sys.Mvc.MvcHelpers.AjaxLoadedContentScriptFix._ajaxOptionsOnSuccess;

    // Call the original MVC onComplete method
    Sys.Mvc.MvcHelpers.AjaxLoadedContentScriptFix._origOnComplete(request, ajaxOptions, ajaxContext);
}

Sys.Mvc.MvcHelpers.AjaxLoadedContentScriptFix._ajaxOptionsOnSuccess = function Sys_Mvc_MvcHelpers_AjaxLoadedContentScriptFix$_onSuccess(ajaxContext) {
    /// <param name="ajaxContext" type="Sys.Mvc.AjaxContext">
    /// </param>

    // Make any dynamically loaded script execute
    Sys.Mvc.MvcHelpers.AjaxLoadedContentScriptFix._globalEvalScriptInElementId(ajaxContext.get_updateTarget());

    // Reinitialise the MVC validation
    Sys.Mvc.MvcHelpers.AjaxLoadedContentScriptFix._reinitialiseMvcValidation();

    // Call the original success delegate
    if (ajaxContext._ajaxLoadedContentScriptFixOrigAjaxOptionsOnSuccess) {
        ajaxContext._ajaxLoadedContentScriptFixOrigAjaxOptionsOnSuccess(ajaxContext);
    }
}

Sys.Mvc.MvcHelpers.AjaxLoadedContentScriptFix._globalEvalScriptInElementId = function GlobalEvalScriptInElementId(element) {
    if (jQuery) {
        // jQuery.globalEval($("#" + element.id).find("script").text());

        // It seems jQuery 1.4.1 &amp; 1.4.2 has a problem in IE with .text() on script nodes� so do the loop ourselves�
        var scripts = $("#" + element.id).find("script");
        var allScriptText = "";
        for (var i = 0; i < scripts.length; i++) {
            allScriptText += scripts[i].text;
        }
        jQuery.globalEval(allScriptText);

    } else {
        alert("Error: jQuery must be loaded in order to use Sys.Mvc.MvcHelpers.AjaxLoadedContentScriptFix");
    }
}

Sys.Mvc.MvcHelpers.AjaxLoadedContentScriptFix._reinitialiseMvcValidation = function Sys_Mvc_MvcHelpers_AjaxLoadedContentScriptFix$ReinitialiseMvcValidation() {
    if (Sys.Mvc.FormContext) {
        Sys.Application.remove_load(arguments.callee);
        Sys.Mvc.FormContext._Application_Load();
    }
}

// Register this extension
Sys.Application.add_load(function () {

    if (typeof (Sys.Mvc) === 'undefined' || typeof (Sys.Mvc.MvcHelpers) === 'undefined' ||
        (!Sys.Mvc.MvcHelpers._onComplete &amp;&amp; !Sys.Mvc.MvcHelpers.$3)) alert("Error: MicrosoftAjax and MicrosoftMvcAjax.js (or their debug versions) must be loaded in order to use Sys.Mvc.MvcHelpers.AjaxLoadedContentScriptFix");

    var isMicrosoftMvcAjaxDebugJs = Sys.Mvc.MvcHelpers._onComplete;

    if (isMicrosoftMvcAjaxDebugJs) { // if using MicrosoftMvcAjax.Debug.js
        Sys.Mvc.MvcHelpers.AjaxLoadedContentScriptFix._origOnComplete = Sys.Mvc.MvcHelpers._onComplete;
        Sys.Mvc.MvcHelpers._onComplete = Sys.Mvc.MvcHelpers.AjaxLoadedContentScriptFix._onComplete;
    } else { // using MicrosoftMvcAjax.js
        Sys.Mvc.MvcHelpers.AjaxLoadedContentScriptFix._origOnComplete = Sys.Mvc.MvcHelpers.$3;
        Sys.Mvc.MvcHelpers.$3 = Sys.Mvc.MvcHelpers.AjaxLoadedContentScriptFix._onComplete;
    }
});

Note: this same technique could be used to hook into the other AjaxOption delegate methods if there was a standard, application-wide action that should take place on each AJAX operation... oh I don't know... for instance: error handling... or an animation...

Update 05/07/2010 - fixed an issue where the script only worked when using the MicrosoftMvcAjax.Debug.js and did not work when using MicrosoftMvcAjax.js. Warning: this script may not work with future versions of the minimised MicrosoftMvcAjax.js.

Update 07/07/2010 - slight tweak to make the check for Sys.Mvc.MvcHelpers happen in the load, and not before we actually need to do it. Some older browsers load the js files out of order and the alert was unnecessarily showing.



comments powered by Disqus