Click here to Skip to main content
15,878,871 members
Articles / Programming Languages / C# 4.0

Silverlight Unsaved Data Detection

Rate me:
Please Sign up or sign in to vote.
4.84/5 (16 votes)
4 Oct 2010Ms-PL4 min read 84.6K   437   19   27
Detect that a user has un-saved changes and popup a box that allows them to stop navigating away from the page (using ViewModel / MVVM)
Image 1

Protect Your Users From Losing Un-Saved Changes

Live example: http://silverlight.adefwebserver.com/UnsavedDataDetection

One of the nice things about using Silverlight for business applications is that the users can enter a lot of information and not worry about the page "timing out". However, if they enter a lot of information and they accidentally navigate away from the page, or they accidentally close the web browser, they will lose any un-saved changes.

This article describes a way to pop up a box, that gives the user an opportunity to save any un-saved changes.

The Sample Application

Image 2

When you load the application, you see the sample information. The Save button is disabled, and the ISDirty checkbox is un-checked.

Image 3

If you make a change and hit the Tab key, the Save button is now enabled, and the ISDirty checkbox is now checked.

Image 4

If you try to navigate away from the page while the form is "Dirty", you will see a Popup that indicates the number of un-saved changes, and asks if you want to continue leaving the page, or if you want to stay and fix any un-saved changes.

Image 5

If you click the Save button, the Save button will be disabled, and the ISDirty checkbox will be un-checked.

You will now be able to navigate away from the page, or close the web browser, and you will not see any warnings.

How LightSwitch Does it

The Microsoft LightSwitch program has this functionality built-in. This is the JavaScript that is used:

JavaScript
  function checkDirty(e) {
    var needConform = false;
    var message = 'You may lose all unsaved data in the application.'; // default message
    
    var silverlightControl = document.getElementById("SilverlightApplication").Content;
    if (silverlightControl) {
        var applicationState = silverlightControl.ApplicationState;
        if (applicationState) {
            if (applicationState.IsDirty) {
                needConform = true;
                message = applicationState.Message;
            }
        }
        else {
            needConform = true;
        }
    }
    
    if (needConform) {
        if (!e) e = window.event;
        e.returnValue = message;
        
        // IE
        e.cancelBubble = true;
        
        //e.stopPropagation works in Firefox.
        if (e.stopPropagation) {
            e.stopPropagation();
            e.preventDefault();
        }
        
        // Chrome
        return message;
    }
}
window.onbeforeunload = checkDirty;

I was surprised because this is all that it uses. Everything else is buried inside the LightSwitch program, and Microsoft is not sharing any of the code. I decided to make my version work using their JavaScript because I figure they spent a lot of money on the best and the brightest people to write it.

There is a surprisingly lack of information on how to do this. I was only able to find one example by Daniel Vaughan, Calling Web Services from Silverlight as the Browser is Closed, that pops up the box like LightSwitch does. However, his example goes into a lot more, such as calling a web service, that I still needed to create my own implementation. However, his example did show me how it is done.

The ApplicationState Class

The basic functionality that I need to implement is:

  • Detect when property has changed (it is Dirty)
  • Detect when a property has changed back to the original value (it is no longer Dirty)
  • Allow all properties to be reset to not Dirty (for example when the Save button is pressed)

Here is the class that does that:

C#
namespace UnsavedDataDetection
{
    public class ApplicationState
    {
        // Properties

        #region IsDirty
        [ScriptableMember]
        public bool IsDirty
        {
            get
            {
                // Return bool if there are Dirty Elements
                return (Elements.Where(x => x.IsDirty == true).Count() > 0);
            }
        }
        #endregion

        #region Message
        [ScriptableMember]
        public string Message
        {
            get
            {
                // Return a message indicating how many Dirty Elements there are
                return string.Format("There are {0} unsaved changes",
                    Elements.Where(x => x.IsDirty == true).Count().ToString());
            }
        }
        #endregion

        // Methods

        #region AddElement
        public void AddElement(ApplicationElement paramElementName)
        {
            // Do we already have the Element?
            var CurrentElement = (from Element in Elements
                                  where Element.ElementKey == paramElementName.ElementKey
                                  select Element).FirstOrDefault();

            if (CurrentElement == null)
            {
                // Ensure that the Element has been marked not Dirty
                paramElementName.IsDirty = false;
                // Set the Initial Value
                paramElementName.ElementInitialValue = 
				paramElementName.ElementCurrentValue;
                // Add the element
                Elements.Add(paramElementName);
            }
            else
            {
                // Update the element
                CurrentElement.ElementCurrentValue = 
				paramElementName.ElementCurrentValue;
                // Set IsDirty
                CurrentElement.IsDirty = (CurrentElement.ElementCurrentValue 
					!= CurrentElement.ElementInitialValue);
            }
        } 
        #endregion

        #region ClearIsDirty
        public void ClearIsDirty()
        {
            // Clear all the ISDirty flags
            foreach (var item in Elements)
            {
                item.ElementInitialValue = item.ElementCurrentValue;
                item.IsDirty = false;
            }
        } 
        #endregion

        // Collections

        #region Elements
        private List<ApplicationElement> _Elements = new List<ApplicationElement>();
        public List<ApplicationElement> Elements
        {
            get { return _Elements; }
            set
            {
                if (Elements == value)
                {
                    return;
                }
                _Elements = value;
            }
        }
        #endregion
    }

    #region ApplicationElement
    public class ApplicationElement
    {
        public string ElementKey { get; set; }
        public string ElementName { get; set; }
        public string ElementCurrentValue { get; set; }
        public string ElementInitialValue { get; set; }
        public bool IsDirty { get; set; }
    }
    #endregion
}

Note that some of the properties are marked, [ScriptableMember], so that they can be called by the JavaScript.

Registering It With the Application

The ApplicationState class needs to be instantiated and invoked on the application level. We open the App.xaml.cs file, and add the following code:

C#
#region ApplicationState
private ApplicationState _objApplicationState = new ApplicationState();
public ApplicationState objApplicationState
{
    get { return _objApplicationState; }
    set
    {
        if (objApplicationState == value)
        {
            return;
        }
        _objApplicationState = value;
    }
}
#endregion

We also add this to the constructor of the application class:

C#
HtmlPage.RegisterScriptableObject("ApplicationState", objApplicationState);

This allows the JavaScript to access the IsDirty and Message properties in the ApplicationState class.

The Implementation

The final step is to implement the functionality in each page of the application. Essentially, we need to register any properties that change with the ApplicationState class and it will do the rest of the work.

First, we start off with a basic ViewModel:

C#
public class HomeViewModel : INotifyPropertyChanged
{
    public HomeViewModel()
    {
        // Set default values
        FullName = "John Doe";
        Email = "JohnDoe@Whitehouse.gov";
    }
    
    // Properties
    
    #region IsDirty
    private bool _IsDirty;
    public bool IsDirty
    {
        get { return _IsDirty; }
        set
        {
            if (IsDirty == value)
            {
                return;
            }
            _IsDirty = value;
            this.NotifyPropertyChanged("IsDirty");
        }
    }
    #endregion
    
    #region FullName
    private string _FullName;
    public string FullName
    {
        get { return _FullName; }
        set
        {
            if (FullName == value)
            {
                return;
            }
            _FullName = value;
            this.NotifyPropertyChanged("FullName");
        }
    }
    #endregion
    
    #region Email
    private string _Email;
    public string Email
    {
        get { return _Email; }
        set
        {
            if (Email == value)
            {
                return;
            }
            _Email = value;
            this.NotifyPropertyChanged("Email");
        }
    }
    #endregion
    
    // Utility
    
    #region INotifyPropertyChanged
    public event PropertyChangedEventHandler PropertyChanged;
    
    private void NotifyPropertyChanged(String info)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(info));
        }
    }
    #endregion
}

We add a PropertyChanged handler to the constructor that will fire whenever any property is changed:

C#
// Wire-up property changed event handler
PropertyChanged += new PropertyChangedEventHandler(HomeViewModel_PropertyChanged);

The implementation of the method is as follows:

C#
#region HomeViewModel_PropertyChanged
void HomeViewModel_PropertyChanged(object sender, PropertyChangedEventArgs e)
{
    // Run this method for any property other than the IsDirty property
    // otherwise you will be in in infinite loop
    if (e.PropertyName != "IsDirty")
    {
        // Create a new ApplicationElement
        ApplicationElement objApplicationElement = new ApplicationElement();
        objApplicationElement.ElementKey = 
		string.Format("HomeViewModel_{0}", e.PropertyName);
        objApplicationElement.ElementName = e.PropertyName;
        
        // Set ElementCurrentValue
        PropertyInfo pi = this.GetType().GetProperty(e.PropertyName);
        objApplicationElement.ElementCurrentValue = 
			Convert.ToString(pi.GetValue(this, null));
        
        // Get an instance of the App class
        App AppObj = (App)App.Current;
        // Add the ApplicationElement to the objApplicationState object
        AppObj.objApplicationState.AddElement(objApplicationElement);
        
        // Set IsDirty
        IsDirty = (AppObj.objApplicationState.Elements.Where
			(x => x.IsDirty == true).Count() > 0);
    }
}
#endregion

Note that the ElementKey is using "HomeViewModel_{0}". You can replace "HomeViewModel" with the name of the current page to easily keep track of multiple pages.

We also add this Save command that will clear all the IsDirty flags:

C#
#region SaveCommand
public ICommand SaveCommand { get; set; }
public void Save(object param)
{
    // Clear IsDirty Flag 
    // (normally you would actually perform a save first)
    
    // Get an instance of the App class
    App AppObj = (App)App.Current;
    
    // Clear all the ISDirty flags
    AppObj.objApplicationState.ClearIsDirty();
    
    // Set IsDirty on this class
    IsDirty = false;
}
private bool CanSave(object param)
{
    // Only enable if form is Dirty
    return (IsDirty);
} 
#endregion

The User Interface (The View)

Image 6

The diagram above shows how the UI is bound to the ViewModel.

Collections (DataGrid)

This does not handle collections. When using a control like the DataGrid, it automatically tracks when the DataGrid is Dirty. I would hook into that property rather than trying to track changes in the DataGrid using the ApplicationState class.

Further Reading

License

This article, along with any associated source code and files, is licensed under The Microsoft Public License (Ms-PL)


Written By
Software Developer (Senior) http://ADefWebserver.com
United States United States
Michael Washington is a Microsoft MVP. He is a ASP.NET and
C# programmer.
He is the founder of
AiHelpWebsite.com,
LightSwitchHelpWebsite.com, and
HoloLensHelpWebsite.com.

He has a son, Zachary and resides in Los Angeles with his wife Valerie.

He is the Author of:

Comments and Discussions

 
GeneralGreat Article Pin
technette4-Nov-10 16:05
technette4-Nov-10 16:05 
GeneralRe: Great Article Pin
defwebserver4-Nov-10 16:57
defwebserver4-Nov-10 16:57 
GeneralMy vote of 5 Pin
Glen Banta13-Oct-10 3:46
Glen Banta13-Oct-10 3:46 
GeneralRe: My vote of 5 Pin
defwebserver21-Oct-10 20:26
defwebserver21-Oct-10 20:26 
GeneralDoesn't seem to work Pin
petervds1238-Oct-10 2:35
petervds1238-Oct-10 2:35 
GeneralRe: Doesn't seem to work Pin
defwebserver8-Oct-10 2:38
defwebserver8-Oct-10 2:38 
GeneralRe: Doesn't seem to work Pin
petervds12311-Oct-10 21:49
petervds12311-Oct-10 21:49 
GeneralRe: Doesn't seem to work Pin
defwebserver12-Oct-10 2:11
defwebserver12-Oct-10 2:11 
GeneralRe: Doesn't seem to work Pin
petervds12312-Oct-10 20:31
petervds12312-Oct-10 20:31 
GeneralRe: Doesn't seem to work Pin
Member 796885015-Jun-11 23:36
Member 796885015-Jun-11 23:36 
GeneralMy vote of 5 Pin
Richard Waddell7-Oct-10 16:34
Richard Waddell7-Oct-10 16:34 
GeneralRe: My vote of 5 Pin
defwebserver7-Oct-10 20:33
defwebserver7-Oct-10 20:33 
GeneralMy vote of 5 Pin
Marcelo Ricardo de Oliveira7-Oct-10 4:06
Marcelo Ricardo de Oliveira7-Oct-10 4:06 
GeneralRe: My vote of 5 Pin
defwebserver7-Oct-10 5:19
defwebserver7-Oct-10 5:19 
GeneralMy vote of 5 Pin
Kunal Chowdhury «IN»6-Oct-10 4:05
professionalKunal Chowdhury «IN»6-Oct-10 4:05 
GeneralRe: My vote of 5 Pin
defwebserver7-Oct-10 13:51
defwebserver7-Oct-10 13:51 
GeneralExcellent Pin
Daniel Vaughan5-Oct-10 23:59
Daniel Vaughan5-Oct-10 23:59 
GeneralRe: Excellent Pin
okaygoods6-Oct-10 0:07
okaygoods6-Oct-10 0:07 
GeneralRe: Excellent Pin
defwebserver6-Oct-10 2:12
defwebserver6-Oct-10 2:12 
GeneralI was looking for something like this... Pin
kackermann5-Oct-10 23:36
kackermann5-Oct-10 23:36 
GeneralRe: I was looking for something like this... Pin
defwebserver6-Oct-10 2:18
defwebserver6-Oct-10 2:18 
GeneralMy vote of 5 Pin
Mamta D4-Oct-10 5:52
Mamta D4-Oct-10 5:52 
GeneralRe: My vote of 5 Pin
defwebserver4-Oct-10 9:30
defwebserver4-Oct-10 9:30 
GeneralInteresting but.... Pin
Sacha Barber4-Oct-10 2:02
Sacha Barber4-Oct-10 2:02 
GeneralRe: Interesting but.... Pin
defwebserver4-Oct-10 2:17
defwebserver4-Oct-10 2:17 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.