How to save a half-completed form

落花浮王杯 提交于 2019-12-22 06:16:33

问题


I am working on a project where we would like to give the user the ability to save their half-completed form so they can come back later and complete it. I'm struggling with figuring out exactly how I want to do this. Do I save them in the same pool with the completed applications, only with a special status? I don't really want to sacrifice the integrity of the completed applications by having to make fields be nullable when I don't want them to be.

Should I create the same database structure in a different schema to hold the incomplete applications? I could have this other schema be more lax on the database contraints and nullable fields to account for incomplete applications.

Is there an easier way to do this? Is there a way I can just save the viewstate and restore that at a later time?

Thanks for any advice!


回答1:


There may be a couple of differences between your completed applications and these "half" states:

  1. As you say, most validation is inappropriate, fields will be null, cross-validations probbably cannot be performed.
  2. You probably don't need arbitrary search capabilities across the data.

So I'd use a different database, with the record comprising a few key fields such as the User's Id, the date, the kind of form they are filling etc. and a blob of the fields they have filled. I'm a Java guy so I don't know the .NET way to get the blob, but in Java I could serialise the data objects backing the form.

It seems like in C# the techniques have some similarity with Java, at least is I understand this article correctly.

I would think that hand-crafting some simple "saveAsAString" and "readFromString" code would be a little dull but pretty doable if no standard .Net techniques exist.




回答2:


I struggled with the same problem. One difference is my method involves ajax auto-saving similar to what you see in Gmail and Blogger. But that shouldn't change the implementation, really.

The trouble was that I didn't want to save into the usual 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're really just trying to leave.

What I finally came up with was a table called AjaxSavedData. It's 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 + "')"



回答3:


You obviously can't save it to the actual data tables, so I'd create a separate table with a userid, formid, and binary data type. Combine the forms into some serializable structure and serialize to the db. When the user comes back, you can deserialize and restore the form state.




回答4:


I'd definitely save it to the database. Your plan to save with a special status (a boolean flag named Complete would work). Then you can create a view which only pulls items where Complete = true, called CompletedApplications.




回答5:


Ever thought of using Silverlight? Silverlight has Isolated Storage, I have seen several examples out there where developers use isolated storage to store expensive client-side data.

http://pietschsoft.com/post/2008/10/Silverlight-Client-Side-Database-via-LINQ-and-Isolated-Storage.aspx

And then using js to get the data in an out:

http://msdn.microsoft.com/en-us/library/cc221414%28VS.95%29.aspx

This keeps you from needing any extra DB space because all the user's temp form entries are stored in Isolated Storage, when they return to the page you ask the user if they want to resume their editing... and then populate the form with the data in isolated storage...

sounds more graceful that adding a new database?

There is a down side that is a machine dependent solution.

Depends on the exact goal of the saving of partial forms? Is it so that it can be brought up on other machines? if so this is not the right solution and a DB save is a better evil.



来源:https://stackoverflow.com/questions/1219275/how-to-save-a-half-completed-form

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!