tags:

views:

471

answers:

2
+1  Q: 

Auto save of form

I have form in ASP.NET 3.5. Where lot of data elements and where i have Save and Submit buttions. I need to auto save my form every 2 min. What is the best way to implement this kind of functionility in ASP.NET.

A: 

Use the Timer class and the Tick method.

Matthew Jones
Ah, sorry I looked again at what you linked to. That could be made to work actually. Although you would be facing the potential validator errors I mention in my answer. And then postbacks can be a little annoying when you don't ask for them. But still, I'd take back the downvote if StackOverflow would let me.
Steve Wortham
+1  A: 

I struggled for awhile with the same problem. The trouble was that I didn't want to save into the usual database tables because that would've required validation (validating integers, currencies, dates, etc). And I didn't want to nag the user about that when they may be trying to leave.

What I finally came up with was a table called AjaxSavedData and making Ajax calls to populate it. AjaxSavedData is a permanent table in the database, but the data it contains tends to be temporary. In other words, it'll store the user's data temporarily until they actually complete the page and move onto the next one.

The table is composed of just a few columns:

AjaxSavedDataID - int:

Primary key.

UserID - int:

Identify the user (easy enough).

PageName - varchar(100):

Necessary if you're working with multiple pages.

ControlID - varchar(100):

I call this a ControlID, but it's really just the ClientID property that .NET exposes for all of the WebControls. So if for example txtEmail was inside a user control named Contact then the ClientID would be Contact_txtEmail.

Value - varchar(MAX):

The value the user entered for a given field or control.

DateChanged - datetime:

The date the value was added or modified.

Along with some custom controls, this system makes it easy for all of this to "just work." On our site, the ClientID of each textbox, dropdownlist, radiobuttonlist, etc is guaranteed to be unique and consistent for a given page. So I was able to write all of this so that the retrieval of the saved data works automatically. In other words, I don't have to wire-up this functionality every time I add some fields to a form.

This auto-saving functionality will be making its way into a very dynamic online business insurance application at techinsurance.com to make it a little more user friendly.

In case you're interested, here's the Javascript that allows auto-saving:

function getNewHTTPObject() {
    var xmlhttp;

    /** Special IE only code */
    /*@cc_on
    @if (@_jscript_version >= 5)
    try {
     xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }
    catch (e) {
     try {
      xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
     }
     catch (E) {
      xmlhttp = false;
     }
    }
    @else
     xmlhttp = false;
    @end
    @*/

    /** Every other browser on the planet */
    if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
     try {
      xmlhttp = new XMLHttpRequest();
     }
     catch (e) {
      xmlhttp = false;
     }
    }

    return xmlhttp;
}

function AjaxSend(url, myfunction) {
    var xmlHttp = getNewHTTPObject();
    url = url + "&_did=" + Date();
    xmlHttp.open("GET", url, true);
    var requestTimer = setTimeout(function() { xmlHttp.abort(); }, 2000);
    xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xmlHttp.setRequestHeader("If-Modified-Since", "Sat, 1 Jan 2005 00:00:00 GMT");
    xmlHttp.onreadystatechange = function() {
     if (xmlHttp.readyState != 4)
      return;
     var result = xmlHttp.responseText;
     myfunction(result);
    };
    xmlHttp.send(null);
}

// Autosave functions
var SaveQueue = []; // contains id's to the DOM object where the value can be found
var SaveQueueID = []; // contains id's for binding references (not always the same)

function ArrayContains(arr, value) {
    for (i = 0; i < arr.length; i++) {
     if (arr[i] == value)
      return true;
    }

    return false;
}

function GetShortTime() {
    var a_p = "";
    var d = new Date();
    var curr_hour = d.getHours();

    if (curr_hour < 12)
     a_p = "AM";
    else
     a_p = "PM";

    if (curr_hour == 0)
     curr_hour = 12;
    else if (curr_hour > 12)
     curr_hour = curr_hour - 12;

    var curr_min = d.getMinutes();
    curr_min = curr_min + "";

    if (curr_min.length == 1)
     curr_min = "0" + curr_min;

    return curr_hour + ":" + curr_min + " " + a_p;
}

function Saved(result) {
    if (result == "OK") {
     document.getElementById("divAutoSaved").innerHTML = "Application auto-saved at " + GetShortTime();
     document.getElementById("divAutoSaved").style.display = "";
    }
    else {
     document.getElementById("divAutoSaved").innerHTML = result;
     document.getElementById("divAutoSaved").style.display = "";
    }
}

function getQueryString(name, defaultValue) {
    var query = window.location.search.substring(1);
    var vars = query.split("&");
    for (var i = 0; i < vars.length; i++) {
     var pair = vars[i].split("=");
     if (pair[0] == name) {
      return pair[1];
     }
    }

    return defaultValue;
}

function urlencode(str) {
    return escape(str).replace(/\+/g, '%2B').replace(/%20/g, '+').replace(/\*/g, '%2A').replace(/\//g, '%2F').replace(/@/g, '%40');
}

function AutoSave() {
    if (SaveQueue.length > 0) {
     var url = "/AjaxAutoSave.aspx?step=" + getQueryString("step", "ContactInformation");

     for (i = 0; i < SaveQueue.length; i++) {
      switch (document.getElementById(SaveQueue[i]).type) {
       case "radio":
        if (document.getElementById(SaveQueue[i]).checked)
         url += "&" + SaveQueueID[i] + "=" + urlencode(document.getElementById(SaveQueue[i]).value);
        break;
       case "checkbox":
        if (document.getElementById(SaveQueue[i]).checked)
         url += "&" + SaveQueueID[i] + "=" + urlencode(document.getElementById(SaveQueue[i]).value);
       default:
        url += "&" + SaveQueueID[i] + "=" + urlencode(document.getElementById(SaveQueue[i]).value);
      }
     }

     SaveQueue = [];
     SaveQueueID = [];
     AjaxSend(url, Saved);
    }
}

function AddToQueue(elem, id) {
    if (id == null || id.length == 0)
     id = elem.id;

    if (!ArrayContains(SaveQueueID, id)) {
     SaveQueue[SaveQueue.length] = elem.id;
     SaveQueueID[SaveQueueID.length] = id;
    }
}

Add this to your page to make this work:

window.setInterval("AutoSave()", 5000);

And to apply this to a Textbox, DropdownList, Listbox, or Checkbox you just need to add this attribute:

onchange="AddToQueue(this)"

...or this for a RadioButtonList or CheckBoxList:

onchange="AddToQueue(this, '" + this.ClientID + "')"

I'm sure this Javascript could be simplified quite a bit if you used JQuery so you might want to consider that. But in any case, AJAX is the thing to use. It's what Google uses to auto-save your email message in gmail, and the same thing is in blogger when you're writing a new post. So I took that concept and applied it to a huge ASP.NET application with hundreds of form elements and it all works beautifully.

Steve Wortham