4

In ASP.NET MVC, what is the preferred pattern for running Javascript on a partial view that is loaded via Ajax?

For example, suppose you need to wire up some click events in your partial view.

Of course, putting something like this in the partial view would not work, because the document ready event won't fire after the partial view is Ajax loaded.

<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 pattern I have been using has been to run any Javascript from my parent view after loading the partial, like this:

$.get(url, function(html) {
    $("#partialDiv").html(html);

    // Now that the partial has loaded...
    RegisterClicks();
});

But I've been working through this example, and noticed that they simply put their click registering code inline in the partial view.

Is this a generally safe pattern to adopt? How can I be sure that the DOM for the partial view has finished loading before my script runs?

5
  • this is a good question. hopefully this post will help stackoverflow.com/questions/3619484/… and this hunlock.com/blogs/Howto_Dynamically_Insert_Javascript_And_CSS Commented Feb 12, 2013 at 18:17
  • 1
    Either I do your second example, have had no problems, but I avoid it because if the partial repeats then the javascript is repeated unnecessarily and is also not minified. Instead I put javascript in an external *.js file and parent pages must include it(and thus if the parent page includes via a bundling/minifying framework it gets minified). I wish Partials had some sort of OnLoadJavascript or supported sections, but unfortunately they don't. Commented Feb 12, 2013 at 20:40
  • We really need this: aspnet.uservoice.com/forums/41201-asp-net-mvc/suggestions/… Commented Feb 12, 2013 at 20:41
  • @AaronLS, if I can ask, as a matter of style, would you have a separate js file for each partial? Or one js file that contained code for all partials? Commented Feb 13, 2013 at 20:32
  • 2
    @Eric Generally one per partial, but sometimes I have a partial page like "_AccountManager.cshtml", which in turn uses a few other child ajax partials like "_AccountTypeSelector.cshtml" for interactive parts of that page. Since that group of partials are always used together under _AccountManager.cshtml, I would have one AccountManager.js that holds all the javascript code for those closely related partials. Commented Feb 13, 2013 at 20:38

2 Answers 2

4

The jQuery .on() function should do the trick, shouldn't it? It should work for dynamically added content.

Have this available as part of the full 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>
Sign up to request clarification or add additional context in comments.

11 Comments

are you sure JQuery.on() will make rendered javascript executable?
Yes, as long as #partialContent exists on the parent page, then any dynamic a.foo's will get wired up. Since this code is specific to the partial though, I'd move it to it's own js file, the parent page would still include that script, but that way it can be minified, externalized, and reused on any parent page that leverages that partial view.
@Eric, the elements would exist. I've created a very simple fiddle to demonstrate that it works.
As @AaronLS mentions, drop the javascript code into it's own .js file that can be included onto any other views that required links wiring up in the same way, as well as the other added benefits described. Hope this helped anyway, mark it as the answer if you wish.
@Eric The element that has to exist is the items selected on the left hand side of .on, the "a.foo" selector on the right hand can be dynamically created. Basically what is happening is you are wiring an event up to #partialContent that says "watch for events that bubble up from a.foo". It's also more efficient for scenarios where you might have thousands of elements, such as td's in a table, because instead of wiring up to thousands of td's(which would create thousands of event handlers) you wire up to a single parent element and let the events bubble up.
|
0
Scripts are not loaded on Partial view via partial view loaded by ajax in Asp.net MVc 

 <div class="modal fade" id="myEditCourseModal" role="dialog">
            <div class="modal-dialog modal-lg">
                <div class="modal-content">
                    <div class="modal-header">
                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                        <h4 class="modal-title text-center">Update Data</h4>
                    </div>
                    <div class="modal-body" id="CourseEditPreview">
                        @Html.Action("CourseUpdatePartial", "AdminCourse")
                    </div>
                </div>
            </div>
        </div>

<script type="text/javascript">

    function OpenCourseEdit(currentId) {
        $.ajax({
            type: "Get",
            url: '@Url.Action("CourseUpdatePartial", "AdminCourse")',
            cache: false,
            Async: true,
            contentType: 'application/html;charset=utf-8',
            dataType: "html",
            data: { CourseID: currentId },
            success: function (data) {
                var content = $('#CourseEditPreview').html(data);
                eval(content);
                $('#myEditCourseModal').modal('show');
            },
            error: function (error) {
                $("#LoadingPanel").css("display", "block");
                $('#CourseEditPreview').html("");
            }
        })
    }
</script>

1 Comment

If you're posting an answer, try to explain why your solution works or is better

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.