1. I have to do a Server-Side condition check first, and then decide whether to call the client side javascript function.
2. My TextBox are all inside an UpdatePanel.
The pure client side solution (like this one) doesn't seem to be a good fit for me. The reason is because the "onunload" event will be called every time when a postback is fired, and the javascript confirm window will always show up. Here is my solution:
1. Setting a mark in the TextBox TextChanged event. This means the data has been modified by client.
protected void gvColumn1_TextChanged(object sender, EventArgs e)
{
int tempValue;
//check the input value
if (int.TryParse(((TextBox)sender).Text, out tempValue))
{
//your logic here
.....
//here is the mark
ViewState["DataChanged"] = true;
}
else
{
//your logic here
.....
}
}
2. Clear the mark at the click event of the "Save" button.
protected void btnSave_Click(object sender, EventArgs e)
{
//your logic here
.....
if (ViewState["DataChanged"] != null)
ViewState["DataChanged"] = null;
}
3. Check the mark if the "Exit", "Next Page", or "Previous Page" button is clicked. If the mark exists, call the javascript to show the confirm window.
protected void btnExit_Click(object sender, EventArgs e)
{
if (ViewState["DataChanged"] != null && (bool)ViewState["DataChanged"]
== true)
{
//your logic here
.....
//build the javascript script
string script = "<script>";
script += "if (confirm('Leave without saving your modifications?'))";
script += "window.location='Default.aspx';"; //redirect to homepage
script += "</script>";
//giving user a chance to save before leaving
ScriptManager.RegisterClientScriptBlock(this, this.GetType(),
"DataNotSave", script, false);
}
else
Response.Redirect("~/Default.aspx"); //redirect to homepage
}
PS: This approach cannot solve the problem if users click the "Previous" or "Next" button on their browsers.
No comments:
Post a Comment