ASP.NET : Dirty Form(data save confirmation on unload form using jquery)


<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript" src="jquery-1.3.2.min.js"></script>
    <script type="text/javascript">
        var initialdata = "nothing";

        $(document).ready(function () {
            initialdata = $('#Panel1 *').serialize();
        });

        function CheckFormDirty() {

            var frmData = $('#Panel1 *').serialize();

            if (WarnIfDirty(frmData)) return false;
        }

        function WarnIfDirty(frmData) {
            if (initialdata != frmData) {
                return !confirm("There is unsaved data on this page. Do you wish to continue?");
            }
            else {
                return false;
            }
        }  

//for unload, if you use unload then not need use it on any other event(ex. button click) because if you will redirect to another page or window then window.onbeforeunloadwill also called. 
     window.onbeforeunload = CheckFormDirty;
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:Panel ID="Panel1" runat="server">
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
            <asp:RadioButton ID="RadioButton1" runat="server" />
            <asp:RadioButton ID="RadioButton2" runat="server" />
            <asp:RadioButtonList ID="RadioButtonList1" runat="server">
            </asp:RadioButtonList>
        </asp:Panel>
        <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="return CheckFormDirty()" />
    </div>
    </form>
</body>
</html>


Note: Disable Pop Blocker or try it with IE.

Also add a jquery file(jquery-1.3.2.min.js) in your project.
Link for download jquery file is: 
http://code.google.com/p/jqueryjs/downloads/detail?name=jquery-1.3.2.min.js&downloadBtn

Comments

Popular posts from this blog

C# Copy files from one server to another

Suppress StyleCop SA1600

Telerik Rad Grid Sorting