MVC Ajax PartialViews not firing Javascript - should I use Spark?
I'm using MVC 2 and the default view engine to return .ascx partial views using the JQuery Ajax .get() method. The partial views have some javascript in them and I'm finding that the behavi开发者_StackOverflow中文版our of the javascript is erratic in that sometimes it executes, while other times it doesn't. I came across a reply from a MS Program Manager on another forum with the following:
"When you update the DOM with new HTML, the browser doesn't automatically execute scripts in the new bit of HTML. Our Ajax helpers would need to parse the partial HTML and try and execute the scripts, which is tricky and something we don't currently do."
I know I can use jquery live events as a workaround, but I was wondering, is this problem specific to the default view engine and would a view engine like Spark resolve the issue? I've never used another view engine before? Thanks for the help !
If you're using jQuery you can do a small hack to get your Javascript to trigger by using the .live() function.
Let's say you include a <div class="javascriptTrigger"></div>
element in your partialView, you should be able to add a jquery to your site.master something like this:
$(document).ready(function(){
$(".javascriptTrigger").live("load", function(){
// Do some javascript
});
});
The .live() function listenes for changes in the DOM and attaches eventhandlers when the trigger is matched.
Might be a possible solution to your problem
No, using a different View engine in this situation would not help. This is something that is happening at the browser level. To simply put it, your AJAX invocation asks the server for a bit of HTML markup and then dynamically injects that piece of markup into the current page's DOM. As quoted, this operation by default does not execute any new javascript that might be contained in that markup.
I resolved the issue in the end using live events. One important point is that in my case I was loading MVC Partial Views and some of those partial views had the same element id's. What this meant was that the live event was binding to multiple elements and firing multiple times. I know call die before I call live to unbind the live event before returning my new partial view.
精彩评论