Auto save function example – ASP.NET

Posted by

When dealing with alot of fields in one single form, user might want to have auto save function. This is something that can help customer to prevent any data lost when submitting the form. 
I know some of you might feel we need to split the form into multiple page. So when user click next, we can save the inputs into session or database, will sometime it is not an option. You just need to deal with alot of fields in one single form. Here I share example how to achieve auto save function using UpdatePanel + Timer in asp.net.   

Use Update Panel. 

This is the part that you need to be careful. Because you cannot wrap the form with UpdatePanel. This is simply because it will cause lagging when customer try to fill in the form. 
Refer below heirarchy to add update panel. 

Script Manager
Update panel
Your form.


Timer is like a countdown time when to trigger the event to save form data. Timer must be put inside UpdatePanel. This is to avoid full postback to server when the event OnTick is triggered. 

Sample Code

Aspx Page

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication2.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <form id="form1" runat="server">
            <asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>
            <asp:UpdatePanel ID="UpdatePanel1" runat="server">
                    <asp:Timer ID="Timer1" Interval="1000" runat="server" OnTick="Timer1_Tick"></asp:Timer>
                    <asp:Literal ID="Literal1" runat="server"></asp:Literal>
            <div class="form">
                <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <button runat="server" id="button1" type="submit"  onserverclick="button1_ServerClick">submit</button>


Code Behind / .cs file

using System;
namespace WebApplication2
    public partial class WebForm1 : System.Web.UI.Page
        protected void Page_Load(object sender, EventArgs e)
        protected void button1_ServerClick(object sender, EventArgs e)
            //do save function here.
        protected void Timer1_Tick(object sender, EventArgs e)
            //get value from textbox and display at front page, You can replace this with your save function
            Literal1.Text = "Value from textbox:" + TextBox1.Text;