Thursday, December 16, 2010

Control Aspx Event on Page Postback

Many of us facec a problem in asp.net pages that is last event fired when user refresh the page.for example if user is adding a record and after adding the record he hits "F5" to refresh the page then the last add event will fire again and insert duplicate record.Below is to handle it.

-----------------------------------------------------------------------------------
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["value"] = Server.UrlEncode(System.DateTime.Now.ToString());
}
}


protected void Page_PreRender(object sender, EventArgs e)
{

ViewState["value"] = Session["value"];

}

protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Session["value"].ToString() == ViewState["value"].ToString())
{
lblMsg.Text = "Button clicked";
Session["value"] = Server.UrlEncode(System.DateTime.Now.ToString());
}
else
{
lblMsg.Text = "Page refreshed";
}
}

-----------------------------------------------------------------------------------



In above example we use a viewstate object and a session object to check if page control event or page refresh event fired. First we set the session object "update" as system datetime on page load when page is first time loaded.after that we set the viewstate value on page_prerender event by passing session object value in it.Now on button click we check if both session and viewstate object values are same. If they are same it means button click fired but if they do'nt match then it means that page is refreshed.The magic here is that whenever page refresh event fired if did'nt refresh the viewstate value but whenever button event fire it return the updated value of viewstate.So when button clicked both value matched but if page refresh then they dnt match.


Thanks & Regards,
Vikas Sharma

No comments:

Post a Comment