Link to home
Start Free TrialLog in
Avatar of VBdotnet2005
VBdotnet2005Flag for United States of America

asked on

close or leave page in asp.net

How to  is trigger an event in code behind when a user try to close a browser or leave a page in aspx? I want to call a sub to insert a row in my database?
Avatar of Kamaraj Subramanian
Kamaraj Subramanian
Flag of Singapore image

Avatar of Eduard Ghergu
Hi,
In code behind it's not possible to trigger an event, because of disconected nature of the web. You'll have to use javascript to capture beforeunload event of the DOM window object. On this event handling, you can perform an ajax call to an inline web method that will handle what you need to update.
Avatar of VBdotnet2005

ASKER

This one?
How about just leave from one page to another page within the same site? How can call a sub?

<script type="text/javascript">
var closing = true;
$(function () {
    $("a,input[type=submit]").click(function () { closing = false; });
    $(window).unload(function () {
        if (closing) {
            jQuery.ajax({ url: "http://localhost:49591/Account/LogOff", async: false });
        }
    });
});
</script>
Hi  ghergu,
Could you provide some code in JS and Ajax call like what you describe above?
I tried this JS below and everytime my page is postback, I got this message.  I have an autocomplete to search for account number. I got this message everytime.


var msg = “Are you sure you want to leave close this page?”;
function ConfirmClose(e) {
 var evt = window.event ? event : e;
 if (evt == e) {
 if (!evt.clientY) {
 evt.returnValue = msg;
 }
 }
 else {
 if (evt.clientY < 0) {
 
evt.returnValue = msg;
 }
 }
 }
Any postback costs this alert to pop up?  I am leaving a page or close a browser, I still get this alert.
The problem I have is that I have autocomplete to search for account number, when it post back, to load data on the page, I get this alert all the time.
window.onbeforeunload = confirmExit;

    function confirmExit() {
        return "Are you sure you want to leave this page?";
    }
ASKER CERTIFIED SOLUTION
Avatar of Eduard Ghergu
Eduard Ghergu
Flag of Romania image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Ghergu,
where do I place above on my page?

$(function(){
   $(window).unload(function() {
// call a function that will perform an AJAX request
// see http://encosia.com/using-jquery-to-directly-call-aspnet-ajax-page-methods/
   });
});