Click here to Skip to main content
15,894,410 members
Articles / Web Development / HTML

AJAX Dirty-Panel

Rate me:
Please Sign up or sign in to vote.
3.79/5 (22 votes)
30 Apr 20072 min read 95.1K   464   60  
This is a Panel that automatically shows an alert if the user tries to leave the page before saving the data.
using System;
using System.Web.UI;
using System.Collections.Generic;
using System.Text;
using ASP = System.Web.UI.WebControls;
using Anthem;
namespace DirtyPanel
{
    public class DirtyPanel : Anthem.Panel
    {
      
        #region Private Members
        private string _onLeaveMessage = "";

        #endregion

        #region Public Properties
        public string OnLeaveMessage
        {
            get { return _onLeaveMessage; }
            set { _onLeaveMessage = value; }
        }
        #endregion

        #region Control State Management

        protected override object SaveControlState()
        {
            object[] state = new object[2];
            state[0] = base.SaveControlState();
            state[1] = this._onLeaveMessage;            
            return state;
        }

        protected override void LoadControlState(object savedState)
        {
            object[] state = (object[])savedState;
            base.LoadControlState(state[0]);
            this._onLeaveMessage = state[1].ToString();
        }
        #endregion

        #region Scripts
        private string GetCurrentValuesScript()
        {
            Dictionary<string, string> controls = new Dictionary<string, string>();            
            RegisterControl(this, controls);

            StringBuilder script = new StringBuilder();
            script.Append("var controls = new Array();");
            script.Append("var values = new Array();");

            int i = 0;
            foreach(KeyValuePair<string, string> control in controls)
            {
                script.Append(string.Format("controls[{0}] = '{1}';", i, control.Key));
                script.Append(string.Format("values[{0}] = {1};", i, control.Value));
                i++;
            }
            return string.Format("<script language=\"javascript\">{0}</script>", script.ToString());
        }

        private void RegisterControl(Control control, Dictionary<string, string> controls)
        {
            if (control.HasControls())
            {
                foreach (Control c in control.Controls)
                    RegisterControl(c, controls);
            }

            if (control is ASP.TextBox)
                controls.Add(control.ClientID, string.Format("'{0}'", ((ASP.TextBox)control).Text));
            else if(control is ASP.DropDownList)
                controls.Add(control.ClientID, ((ASP.DropDownList)control).SelectedIndex.ToString());
            else if (control is ASP.CheckBox)
                controls.Add(control.ClientID, ((ASP.CheckBox)control).Checked.ToString().ToLower());
            else if (control is ASP.RadioButton)
                controls.Add(control.ClientID, ((ASP.RadioButton)control).Checked.ToString().ToLower());
        }

        private string GetDefaultScript()
        {
            return @"<script language='javascript'>
           window.onbeforeunload = function (oEvent) 
           {
                if(IsDirty() == true)
                {
                    if(!oEvent) oEvent = window.event;
                    oEvent.returnValue = '" + this._onLeaveMessage + @"';
                }    
           }
           
           function IsDirty()
           {
                var i=0;
                for (i=0; i< controls.length; i++)
                {                    
                    var control = document.getElementById(controls[i]);
                    if(control.type == 'text' || control.type == 'textarea')
                    {
                        if(control.value != values[i])
                            return true;
                    }
                    else if(control.type == 'select-one')
                    {
                        if(control.selectedIndex != values[i])
                            return true;
                    }
                    else if(control.type == 'checkbox' || control.type == 'radio')
                    {
                        if(control.checked != values[i])
                            return true;
                    }
                }           
                return false;
           }
            </script>";
        }
        #endregion

        protected override void Render(HtmlTextWriter writer)
        {
            writer.Write(GetDefaultScript());
            writer.Write(GetCurrentValuesScript());
            base.Render(writer);
        }

        public void Reset()
        {
            this.UpdateAfterCallBack = true;
            Anthem.Manager.IncludePageScripts = true;
            
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
Software Developer (Senior) Intelligent Coder
Canada Canada
I've been developing .NET enterprise applications since 2000.

I am originally from Rio de Janeiro and I am currently working at http://www.intelligentcoder.com in Ontario.

I also have my own startup where we offer client intake forms.

Comments and Discussions