Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

detecting page close (or unload) in asp.net mvc3

I am building a MVC3 app and on few pages I need to perform few action when the user navigates away from the page.

For example if the user is on page X and clicks any other link I need to perform actions A,B,C

The implementation I have so far uses filters and detects if the user navigates to any other page from page X.

This works except if the user open the link on page X in anther tab. i.e the page X is still open but the user has navigated to another page and actions A, B, C and performed. This not suppose to happen since page X is still open.

I was wondering if there is way to detect page close even on page X so I only perform the action when the page is closed or unloaded ?

like image 963
keshav Avatar asked Apr 22 '12 18:04

keshav


1 Answers

You can use jQuery's .unload functionality paired with an ajax post to accomplish this from the front end.

$(window).unload(function() {
 //ajax post to controller action
 $.ajax({
        type: 'POST',
        url: '/Controller/Action',
        data : { param1 : "value1", param2: "value2" },
        dataType: 'html',
        success: //do what needs to be done here, alert?
    });
});
like image 131
Travis J Avatar answered Nov 01 '22 05:11

Travis J