Friday, 16 January 2015

In todays post i will tell you how you can avoid repeated insertion of records into database due to page refresh.
     In asp.net when you insert a record the page posts back to the server and when ever you refresh the page that postback is repeated due to which the record is inserted again into the database. This is a big problem we don't want that so we want to avoid postback on page refresh.
   So here are the ways you can handle this problem.

  •    By avoiding the duplicate postback
  •    By redirecting to another page after saving data
  •    By using ViewState to check if data is already inserted
Here we will use the third method we will use a flag to check if the data is already inserted or not
 here is the markup for the page:
Markup:

1:  <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
2:  <!DOCTYPE html>  
3:  <html xmlns="http://www.w3.org/1999/xhtml">  
4:  <head runat="server">  
5:    <title></title>  
6:  </head>  
7:  <body>  
8:    <form id="form1" runat="server">  
9:    <div>  
10:      <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Insert Data" />  
11:    </div>  
12:    </form>  
13:  </body>  
14:  </html>  

CSharp:
1:  using System;  
2:  using System.Collections.Generic;  
3:  using System.Linq;  
4:  using System.Web;  
5:  using System.Web.UI;  
6:  using System.Web.UI.WebControls;  
7:  public partial class _Default : System.Web.UI.Page  
8:  {  
9:    protected void Page_Load(object sender, EventArgs e)  
10:    {  
11:      if (!IsPostBack)  
12:        ViewState["HasPosted"] = false;  
13:    }  
14:    protected void Button1_Click(object sender, EventArgs e)  
15:    {   
16:      bool posted = (bool)ViewState["HasPosted"];  
17:      if (!posted)  
18:      {  
19:        //Data Insertion code here  
20:        //here you can do the tasks which you want do to do just on the the first click of the button for example inserting data into database  
21:        Response.Write("<script type='text/javascript'>alert('Data Inserted Successfully!!');</script>");  
22:        ViewState["HasPosted"] = true;  
23:      }  
24:      else Response.Write("<script type='text/javascript'>alert('Already Inserted');</script>");  
25:      }  
26:  }  

When the page loads the first time a ViewState  "HasPosted" is stored with value false and when data is inserted the value is changed to true. Data can only be inserted once by using this technique. When you press the insert button again after first insertion an error  message will popup and if you try to repeat the insertion by refreshing the page you will see the error message.

Avoid Repaeted Insertion on Page Refresh


Subscribe to RSS Feed Follow me on Twitter!