Javascript: How to cancel leaving page without saving

Preparing the javascript:
string jscript = "var needToSave= false;" +
"window.onbeforeunload = confirmExit;" +
"function confirmExit(){" +
"if (needToSave){" +
"return 'Are you sure you want to leave the page without saving?';" +
"}" +

Registering the script - safe for ajax:

ScriptManager smgr = ScriptManager.GetCurrent(Page);
ScriptManager.RegisterStartupScript(this.Page, this.GetType(), "temp", "", false);

On every field that changes the data and requires saving put:
control.Attributes.Add("onkeydown","javascript: needToSave=true;")

on the button that make save postback add:
control.Attributes.Add("onclick","javascript: needToSave=false;")

No comments:

Post a Comment