自动保存表格

发布于 2024-08-05 12:50:16 字数 97 浏览 1 评论 0原文

我有 ASP.NET 3.5 中的表单。其中有很多数据元素,并且我有“保存”和“提交”按钮。我需要每 2 分钟自动保存一次表单。在 ASP.NET 中实现此类功能的最佳方法是什么?

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

拔了角的鹿 2024-08-12 12:50:16

我为同样的问题苦苦挣扎了一段时间。问题是我不想保存到通常的数据库表中,因为这需要验证(验证整数、货币、日期等)。当用户可能试图离开时,我不想再向他们唠叨这一点。

我最终想出了一个名为 AjaxSavedData 的表,并通过 Ajax 调用来填充它。 AjaxSavedData 是数据库中的永久表,但它包含的数据往往是临时的。换句话说,它将临时存储用户的数据,直到他们实际完成页面并转到下一页。

该表仅由几列组成:

AjaxSavedDataID - int:

主键。

UserID - int:

识别用户(足够简单)。

PageName - varchar(100):

如果您正在处理多个页面,则有必要。

ControlID - varchar(100):

我将其称为 ControlID,但它实际上只是 .NET 为所有 WebControl 公开的 ClientID 属性。因此,如果 txtEmail 位于名为 Contact 的用户控件内,则 ClientID 将是 Contact_txtEmail。

- varchar(MAX):

用户为给定字段或控件输入的值。

DateChanged - 日期时间:

添加或修改值的日期。

与一些自定义控件一起,该系统使所有这些都可以轻松“正常工作”。在我们的网站上,每个文本框、下拉列表、单选按钮列表等的 ClientID 保证对于给定页面是唯一且一致的。因此,我能够编写所有这些内容,以便自动检索保存的数据。换句话说,我不必每次向表单添加一些字段时都连接此功能。

这种自动保存功能将被纳入 techinsurance.com 上一个非常动态的在线商业保险应用程序中,使其更加用户友好。

如果您有兴趣,这里是允许自动保存的 Javascript:

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;
    }
}

将其添加到您的页面以使其工作:

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

并将其应用于文本框、下拉列表、列表框或复选框,您只需添加此属性:

onchange="AddToQueue(this)"

.. .或者用于 RadioButtonList 或 CheckBoxList:

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

我确信如果您使用 JQuery,这个 Javascript 可以被简化很多,所以您可能需要考虑这一点。但无论如何,AJAX 是可以使用的。 Google 使用它来自动将您的电子邮件保存在 gmail 中,当您撰写新帖子时,Blogger 中也会使用同样的功能。因此,我采用了这个概念并将其应用到一个包含数百个表单元素的大型 ASP.NET 应用程序中,并且一切都运行得非常好。

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.

通知家属抬走 2024-08-12 12:50:16

使用 Timer 类和 Tick 方法。

Use the Timer class and the Tick method.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文