Thursday, April 2, 2009

Restrict Duplicate Record Insertion On Page Refresh

The two ways which I believe is pretty simple to prevent duplicate record insertion on page refresh.

1. Using ViewState and Session


public partial class _Default : System.Web.UI.Page
{
private bool _refreshState;
private bool _isRefresh;
public bool IsRefresh
{
get
{
return _isRefresh;
}
}
protected override void LoadViewState(object savedState)
{
object[] allStates = (object[])savedState;
base.LoadViewState(allStates[0]);
_refreshState = (bool)allStates[1];
_isRefresh = _refreshState == (bool)Session["__ISREFRESH"];
}

protected override object SaveViewState()
{
Session["__ISREFRESH"] = _refreshState;
object[] allStates = new object[2];
allStates[0] = base.SaveViewState();
allStates[1] = !_refreshState;
return allStates;
}

protected void Button2_Click(object sender, EventArgs e)
{
if(!IsRefresh)
Response.Write("Thanx for visiting");
}
}




2. Use Response.Redirect


public partial class _Default : System.Web.UI.Page
{

protected void Page_Load(object sender, EventArgs e)
{
Boolean blnRefreshed = true;
}
protected void Button1_Click(object sender, EventArgs e)
{
//code to save your data here
Response.Redirect("default.aspx");
}

}


The second one has a performance overhead. Let’s check how.
Put break point on Page_Load and click on button. The break points on Page_Load will be hit twice intead of one due to Response.Redirect, the second hit is overhead.

The second hit can be avoided by using the first method.

Happy Coding :)

4 comments:

DotNetRuler said...

It Would be Higly Helpful What have yo done in your First method...

Anonymous said...

Thanks for solution.First method is very useful.

Neha Mayank Dubey said...

Hi,

it's giving error under LoadViewState "Unable to cast object of type 'System.Collections.ArrayList' to type 'System.Object[]' in loadviewstate". Please advise.

stevanus w said...

method 1 is very smart ;)

Site Meter