0

Following is my view which contains a div in which partial views are rendered based on actions performed in the view.

//Boiler Plate HTML
<div id="PartialViewHolder">
        @Html.Partial(Model.PartialView, Model)
</div>
//Boiler Plate HTML

The partial views are rendered via an ajax call which is as follows

//The url is supplied based on some actions in the main view
function AjaxCall(url){
    $.ajax({
        url: url,
        cache: false,
        success: function (html) {
            $("#PartialViewHolder").empty();
            $("#PartialViewHolder").html(html);
        },
        error: function (result) {
            alert("Error: " + result.status + ": " + result.statusText);
        }
    });
}

The main page also loads a few other scripts which are common to the partial views. These scripts work when the page is first rendered, i.e when the default partial view is rendered. However these scripts stop working for partial views which are loaded by the ajax call. I believe that these scripts need to be reloaded when the DOM elements change. I am looking for a clean way to reload those scripts when the partial view div is reloaded.

1 Answer 1

3

You need to do a bit of reading about Event binding. http://api.jquery.com/on/

Tricky to understand at first but worth it once you do.

Assuming you've got some code like this.

<div class="container">
    <div class="partial">
        <a href="#" class="magic-link">Click here to do stuff</a>
    </div>
</div>

JS Code like the example below will only work for objects present when you do the binding (usually document.ready()) It seems like this is the situation you are describing.

$(".magic-link").click(function(){
    alert("Magic link clicked");
    return false;   
})

If you want the event to fire on objects that haven't yet been loaded onto the page then you need to bind an event handler to the container div i.e. the bit which doesn't change. Like this

$(".container").on("click", ".magic-link", function(){
    alert("Magic link clicked");
    return false;
});

The event bubbles up to the event handler and fires the event. This has another advantage that one event handler and potentially handle events from hundreds of objects. As a guideline try to bind the listener to the nearest parent object that will not change. In the case of the example this is the Container div. This keeps the bubbling to a minimum.

Sign up to request clarification or add additional context in comments.

1 Comment

Does this answer your question? Feel free to accept it if it does, or comment if you need clarification.

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.