This will show how to auto save a web form in the background without affecting user input.
I was working with a large form and was looking for an easy way to do an auto save so that the data would not get lost if the session timed out or for some other reason when the user did not click save button. I found some examples which were not so easy to implement. I just wanted to do the same function as when clicking the save button. I then tried some ways to do this with the AJAX controls and found it to be super easy.
Using the Code
The code in this article is simple by just moving the text form one textbox to another. But this can be replaced to do the actual saving of the form content (for example, to a database).
To do this, first create a form and your form fields. Then add a
Timer and an
UpdatePanel from AJAX Extensions tab in the Toolbox.
If you do not want anything to be displayed when saving, leave the
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
<asp:Timer ID="Timer1" runat="server" Interval="15000" ontick="Timer1_Tick"></asp:Timer>
<asp:TextBox ID="TextBox1" runat="server"
Height="118px" TextMode="MultiLine" Width="468px"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Save"
onclick="Button1_Click" /><br /><br />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<asp:TextBox ID="TextBox2" runat="server" Height="120px"
<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick"/>
In the code behind, the save button click event calls the
save method which in this case only copies the text between the textboxes:
protected void Button1_Click(object sender, EventArgs e)
private void Save()
TextBox2.Text = TextBox1.Text;
The only thing now is to add a handler for the timer
onTick event and make that call the same
protected void Timer1_Tick(object sender, EventArgs e)
Now it is done!
Points of Interest
The key thing here is the
AsyncPostBackTrigger. Without the trigger, the form will do a postback and the form will flicker for the user and lose focus on the current form field (and you don't want that to happen on a time interval when you write a long text).
- 20th March, 2009: Initial post
- 25th March, 2009: Made some minor text changes