This is an unofficial update to a recent MSDN Online article I wrote titled Working with Client-Side Script. In that article I examined a number of common client-side tasks, and looked at how to accomplish them easily with ASP.NET by extending the Page class. Specifically, I looked at how to do things like: display an alert dialog box; how to display a confirm dialog box when deleting or performing other “Are you sure you really, really want to do this?”-type of activities; how to display a popup window; and how to alert the user if they're about to leave a page from which they've made changes but have yet to save those changes.
In my article I accomplished the last common task by adding methods to the extended Page class that allowed a page developer to easily add a client-side onchange event to the data-entry Web controls that would set a flag indicating they had been modified. Then, when leaving the page through a button click, hyperlink, etc., the user would be prompted with a standard confirm dialog asking them if they were sure they wanted to leave the page (assuming that the dirty flag was true).
This approach had two drawbacks:
- It flagged the data as dirty from a simple change. That is, if a user changed a textbox value from “Scott“ to “Jisun“ and then back to “Scott,“ when leaving the page they'd be warned that they were leaving without saving. This warning would happen because the data had been altered at least once, even though it had been changed back to its original value.
- If the user left the page through some other means (i.e., not necessarily by clicking on some navigational Web control), then they could leave the page without the warning. Ideally the user would receive a warning if they closed their browser, typed in another URL in their browser's Address bar, or even clicked a link in, say, Outlook, that redirected that browser instance to another page.
Last week on 4Guys I wrote an article - Prompting a User to Save When Leaving a Page - that looked at how to use the client-side onbeforeunload event and some clever JavaScript. The onbeforeunload event fires whenever the document is unloading, and gives the developer a chance to prompt the user. The user can choose to either continue with the unloading of the document, or can stop it outright. This works even if they attempt to close the browser window. (One caveat is that there's not standard browser support for onbeforeunload. IE supports it, as does FireFox 0.9+.)
Today I wrote an article titled Using ASP.NET to Prompt a User to Save When Leaving a Page. This article looks at how to extend the Page class to include methods to easily add this onbeforeunload support to your ASP.NET data-entry forms. This article serves, in a roundabout way, as an update for the technique examined in the MSDN article. (Although the MSDN article's approach is more compatible with non-standard browsers.)