如何在ASP.NET中实现“自动保存”或“保存草稿”的功能?

7
我有一个ASP.NET 2.0的注册表单,我想要在点击提交按钮时保存我的注册表单字段,或者每五秒钟自动保存一次。
例如,我的注册页面有三个字段:
UID PWD Name 当用户输入UID和PWD并在输入Name时,之前的值应该被保存而不会中断用户的输入。
如何在ASP.NET中实现这个功能?
1个回答

9
你可以使用一小段Javascript和jQuery来实现这个功能。编写一个由定时器触发的函数,定期读取要保存的表单数据并将其发送回SaveDraft.aspx页面。在此页面上将数据持久化存储在某个地方(例如数据库)。
如果用户注销或会话丢失,您可以查询这些数据,如果存在,则预填充表单。
在你的数据输入ASPX页面上:
// Usual ASP.NET page directives go here

<html xmlns="http://www.w3.org/1999/xhtml">
  <head runat="server">
    <script type="text/javascript" src="Scripts/jquery-1.4.1.min.js" ></script>
  </head>
  <body>
    <form id="form1" runat="server">
      <div>
        <asp:textbox id="username" runat="server" /><br />
        <asp:textbox id="password" runat="server" /><br />
        <asp:textbox id="realName" runat="server" /><br />
        <asp:button id="Submit" onclick="Submit_Click" 
              usesubmitbehavior="true" runat="server" />
      </div>
    </form>

    <script type="text/javascript">
      $(document).ready(function () {
        // Configure to save every 5 seconds
        window.setInterval(saveDraft, 5000);
      });

      // The magic happens here...
      function saveDraft() {
        $.ajax({
          type: "POST",
          url: "SaveDraft.aspx",
          data: ({
            username: $("#<%=username.ClientID %>").val(),
            password: $("#<%=password.ClientID %>").val(),
            realName: $("#<%=realName.ClientID %>").val()
          }),
          success: function (response) {
            alert('saved draft');
          }
        });
      }
    </script>
  </body>
</html>

在您的SaveDraft.aspx页面中:

public partial class SaveDraft : System.Web.UI.Page
{
  protected void Page_Load(object sender, EventArgs e)
  {
    string username = Request.Form["username"];
    string password = Request.Form["password"];
    string realName = Request.Form["realName"];

    // Save data somewhere at this point    
  }
}

那应该能让你开始了。

在VB .net中,Response.Form ["username"];的等效语句是什么? - Dogahe
@Dogahe Response.Form("username") - VB使用圆括号而不是方括号。 - Kev
@Dogahe - 需要看一下你的代码才能理解原因。这是一个ASP.NET Forms还是ASP.NET MVC应用程序? - Kev
@Kev,这是我发布的一个问题:http://stackoverflow.com/questions/13278616/reading-jqurey-ajax-url-call-data-in-vb-net-code-behind,这是我使用你的代码后的经验。一切都正常工作,也就是说每5秒钟我都会进入SaveDraft的Page_load事件。但我不知道的是,当我在那里时,如何读取文本框的值,我的情况是dataTextBox。FYI:我是一个非常有经验的程序员,但我几乎没有任何JavaScript或jQuery的经验。 - Dogahe
我认为应该是 Request.Form[""] 而不是 Response.Form[""],如果我错了请纠正我。 - Prakash
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接