0

I am using asp.net and I need to display a prompt to the user if they have made changes to the web page, and they accidentally close down the browser.

The page could be anything from "Edit Profile" to a "Submit a Claim" etc.

How can I can display the messagebox, ensuring that it is displayed only if changes have been made (as opposed to, the user making changes, then undo-ing the changes, and shutting down the browser)

user279521
  • 4,779
  • 21
  • 78
  • 109

3 Answers3

1

That's very difficult to even touch without understanding what's on the page. If it's a few controls you capture value at page load and store them so you can later compare. If it's a complex page you'd need to do an exact comparison to the entire viewstate.

Typically you'd handle this type of situation by setting a boolean to TRUE the first time any change is made and disregard the user changing it back. If you're just trying to avoid accidential non-save of data the user should be smart enough to know they've "undone" their changes.

RogerG
  • 258
  • 1
  • 7
  • Makes good sense. Thats a great answer. Though how would I compare to a viewstate (syntax I mean)? – user279521 Dec 10 '10 at 20:03
  • You could compare to viewstate during a post back however you can't use this method reliably. If I shut down the browser or navigate to a different page your note going get the post back. I would not recommend trying to parse the viewstate client side. – JoshBerke Dec 10 '10 at 20:22
1

What I have done in the past is use some client side scripting which does this check during the onbeforeunload event....

var showPrompt=true;
var isDirty=false;
var hidePopup=false;

    function onBeforeUnload() {
        if (showPrompt) {
            if (isDirty) {
                if (hidePopup || confirm("Click ok to save your changes or click cancel to discard your changes.")) {
                    doSave();
                }
            }
        }
        showPrompt = true;
        hidePopup = false;
    }
  • ShowPrompt can be set to false when your clicking on an anchor tag which won't navigate you away from the page. For example <a onclick='showPrompt=false' href='javascript:doX()'/>
  • isDirty can be used to track when you need to save something. You could for example do something like $("input").onchange(function(){isDirty=true;}); To track undo's you might want to replace isDirty with a function which checks the current state from the last saved state.
  • HidePopup lets us force a save without confirming to the user.
JoshBerke
  • 66,142
  • 25
  • 126
  • 164
1

You can do this with javascript. See this question and either of the first two answers.

Community
  • 1
  • 1
Jason
  • 51,583
  • 38
  • 133
  • 185