javascript 如何在 ASP.NET 中实现“自动保存”或“保存草稿”功能?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3889004/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to implement an "Auto Save" or "Save Draft" feature in ASP.NET?
提问by Sandy
I have a registration form in ASP.NET 2.0. I want to save my registration form fields either by clicking on submit button or they should be saved every five seconds.
我在 ASP.NET 2.0 中有一个注册表单。我想通过单击提交按钮来保存我的注册表单字段,或者每五秒钟保存一次。
For example I have three fields in my registration page:
例如,我的注册页面中有三个字段:
UIDPWDName
UIDPWDName
The user has entered UIDand PWDand whilst he is entering Namethe previous values should be saved without interruption of user inputs
用户已经输入UID,PWD并且在输入Name之前的值时,应在不中断用户输入的情况下保存
How would I do this in ASP.NET?
我将如何在 ASP.NET 中执行此操作?
回答by Kev
You could do this with a snippet of Javascript & jQuery. Have a function that's fired by a timer that periodically reads the form data you want to save and posts it back to a SaveDraft.aspxpage. In this page persists the data somewhere (such as a database).
你可以用一段 Javascript 和 jQuery 来做到这一点。有一个由计时器触发的函数,该计时器定期读取您要保存的表单数据并将其发布回SaveDraft.aspx页面。在此页面中,将数据保存在某处(例如数据库)。
If the user logs out or their session is lost you can query for this data and pre-populate the form if the data exists.
如果用户注销或他们的会话丢失,您可以查询此数据并在数据存在时预填充表单。
On your data entry ASPX page:
在您的数据输入 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>
In your SaveDraft.aspxpage:
在您的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
}
}
That should get you started.
这应该让你开始。

