views:

910

answers:

3

On StackOverflow when you're asking a new question, you have enter the question and if you decide to navigate away from the page you get an "Are you sure" confirmation.

I'd like to do the same in my ASP.Net application:

The user has to fill in a questionnaire and has the option to store his answers temporarely. If the user decides to navigate away from the page without temporarely storing his answers we'd like a confirmation to popup and ask the user to store his answers.

Two questions:

  • What's a decent way of showing the confirmation popup before the page unloads in ASP.Net?
    I'm aware of the beforeunload event, but I don't want to make it one big javascript hack.

  • I don't want the confirmation to kick in when the user clicks the Save button (which is saving the answers anyway)

+3  A: 

You have to write the action in

onbeforeunload Event

which fires prior to a page being unloaded.

<HTML>
<head>
<script>
function closeIt()
{
  return "Any string value here forces a dialog box to \n" + 
         "appear before closing the window.";
}
window.onbeforeunload = closeIt;
</script>
</head>
<body>
  <a href="http://www.microsoft.com"&gt;Click here to navigate to 
      www.microsoft.com</a>
</body>
</html>
rahul
I'm aware of the onbeforeunload event. However you're going to have to hack yourself into the form submit or button click code to make the exception for that specific button. I was wondering if there is a better way to do that with ASP.net. Thnx.
Zyphrax
A: 

You should pay your attention on "onbeforunload" event As for the Save button you just can make some scripting logic, for example unsubscribe on this event or else.

Restuta
Same comment as the answer above.
Zyphrax
Do not agree with "you're going to have to hack yourself" it is very easy to write such logic. It is no better way and espesially in ASP.NET that is also weak before client logic.
Restuta
A: 

You can try this:

<button onclick="javascript:doSend()">send</button>
<button onclick="window.xbuttons +='save ';">save</button>
<button onclick="window.xbuttons +='edit';">edit</button>
<script>
   window.xbuttons = '';
   window.onbeforeunload = function(){
      if(!window.xbuttons.match(/save|edit/))
         return "Do you want to leave this page?";
   }
</script>

Here are the things you should note about onbeforeunload:

  1. onbeforeunload event will fire on every a (anchor elements) with href attribute
  2. onbeforeunload event will fire when the document location is change via javascript or by changing the url on the address bar
  3. onbeforeunload event will fire on any event that uses javascript: pseudo-protocol
jerjer