How do I handle javascript in ajax loaded partial view?
In ASP.NET MVC, what's the preferred pattern for running Javascript on a partial view loaded via Ajax?
For example, suppose you need to bind some click events in a partial view.
Of course, something like this in partial view won't work, because the document ready event doesn't fire after the partial Ajax view.
<script type="text/javascript">
$(function() {
$("a.foo").click(function() {
foo();
return false;
});
});
</script>
I suppose something like this might work, but is it safe?
<script type="text/javascript">
$("a.foo").click(function() {
foo();
return false;
});
</script>
The sample I used was to run any Javascript from my parent view after loading the partial, for example:
$.get(url, function(html) {
$("#partialDiv").html(html);
// Now that the partial has loaded...
RegisterClicks();
});
But I was working on this example and noticed that they just insert their click registration code into the partial view.
Is this a generally accepted pattern? How can I be sure that the DOM for the partial view has finished loading before the script runs?
source to share
The jQuery.on () function should do the trick, right? It should work for dynamically added content.
You have it as part of the complete content
<script type="text/javascript">
$(function() {
$("#partialContent").on("click", "a.foo", function() {
foo();
return false;
});
});
</script>
<div id="partialContent">
<a href="#" class="foo">Link 1</a>
<a href="#" class="foo">Link 2</a>
<!-- More dynamic content -->
</div>
source to share