0

My objective is to save the data if the user did not click the save button and wants to exit or navigate to another page in MVC.

I didn't find any help on how to do this. So far I have come across the OnBeforeUnload method in jquery but it only shows the message on exiting and it does not call the MVC controller method.

How can I accomplish this?

Alex
  • 1,549
  • 2
  • 16
  • 41
ovais
  • 339
  • 2
  • 13
  • Have a look here: http://stackoverflow.com/questions/13443503/run-javascript-code-on-window-close - first answer. – Nikel Weis Jun 05 '14 at 07:00
  • Yes i look at it but the problem here is that ajax call is not supported in the OnBeforeUnload method. This method is meant only for the display of messages. https://developer.mozilla.org/en-US/docs/Web/API/Window.onbeforeunload – ovais Jun 05 '14 at 07:08
  • Shouldn't you rather ask your user if he's sure to exit the page and advise to save the data? Background saving without asking can have unintended side effects (for example I close web pages BECAUSE I don't want data to be saved). Ok - but that wasn't the question... – Nikel Weis Jun 05 '14 at 07:19
  • No but i need the data to be saved silently for Administrative purposes. This data won't include anything that the user don't like to save. – ovais Jun 05 '14 at 07:30

1 Answers1

0

I think this may be what you're looking for

window.onbeforeunload = closeSession;
function closeSession(){
    $.ajax({
        url: "/yourmvcfile.php",
        async : false
    });
}
Andy Gee
  • 3,149
  • 2
  • 29
  • 44
  • Thanks Andy Gee but onbeforeunload doesn't work like this. It returns a string and gives the user a chance to reply to a prompt: developer.mozilla.org/en-US/docs/Web/API/Window.onbeforeunload – ovais Jun 05 '14 at 06:51
  • Can't you just add an return null? Should work. There are a lot of posts on stackoverflow on that topic - just search onbeforeunload ajax. – Nikel Weis Jun 05 '14 at 07:25