Monday, April 28, 2008

Warning the User About Prematurely Leaving a Web Page

I'm relatively new to website development. Up until now I've never had occasion to warn the user about leaving a web page. I knew it was possible though, as I'd seen it on some websites before.

I'm now working on a data editor that looks like this:

Essentially, the user can pick one of several bottom-level nodes in the treeview on the left and then the data associated with it will be displayed in the controls on the right. He might just view this data or may alter it. He can also add & delete & move nodes, each of which is connected with a data record.

A novice user wouldn't understand that all changes are handled locally and not updated in the database until 'Save' is pressed. So letting them enter a bunch of data and then close the browser or navigate to another page simply wasn't acceptable.

I found this article by well known ASP.Net guru, Scott Mitchell. It's actually the third in a trilogy of articles on the subject. I followed the basics of what he wrote and added this code to my ASPX page:

var needToConfirmExit = false; // Initialize

function ConfirmExit()
{
needToConfirmExit = Boolean(document.getElementById('<%= needToSaveData.ClientID %>').value);
if (needToConfirmExit)
return "You have made changes that have not yet been saved back to the database. If you leave now, all of those changes will be lost. Are you absolutely sure you want to do this?";
}

window.onbeforeunload = ConfirmExit;


The more advanced part of his article dealt with implementing an extensive client-side mechanism that kept track of which controls had their values changed. As my web page was AJAX enabled, partial page updates were occurring whenever any control's value was altered. So intuitively I knew there must be a simpler way

In the server-side code I already had a property called 'IsDirty' :

public bool IsDirty
{
get
{
return (bool)ViewState["IsDirty"]; // Note: If null then returns as false
}
set
{
ViewState["IsDirty"] = value;
ChangeButtonState(Constants.CommandButtons.Save, value);
needToSaveData.Value = value.ToString().ToLower();
}
}

'needToSaveData' is a hidden field that I placed inside the UpdatePanel. The beauty of this solution is that as soon as a control is updated, the 'ConfirmExit' JavaScript function is ready to go in case the user tries to prematurely leave the web page.

No comments:

Post a Comment