Sunday, December 30, 2012

Detect Browser Refresh to avoid events fired again in ASP.NET


If you have created an aspx page using C# and ASP.NET and have put a button on it. And in the Click event of this button if you are inserting some data in database , after click if user refresh the page than click event gets fired again resulting data insertion to database again, to stop events on the page getting fired on browser refresh we need to write bit of code to avoid it.

In this example I’ve put a Label and a Button on the page, on click the label Text becomes Hello and when I refresh the page label's text again becomes Hello

Markup




Now in the Page_Load event I m creating a Session Variable and assigning System date and time to it , and in Page_Prerender event I am creating a Viewstate variable and assigning Session variable's value to it than in button's click event I am checking the values of Session variable and Viewstate variable if they both are equal than page is not refreshed otherwise it has been refreshed 

  
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["CheckRefresh"] =
Server.UrlDecode(System.DateTime.Now.ToString());
}
}
protected void imgbtn_Click(object sender, ImageClickEventArgs e)
{
//Label2.Text = imgbtn.ToolTip;
}
protected void Button1_Click(object sender, EventArgs e)
{
if (Session["CheckRefresh"].ToString() == ViewState["CheckRefresh"].ToString())
{
Label1.Text = "Hello";
Session["CheckRefresh"] =
Server.UrlDecode(System.DateTime.Now.ToString());
}
else
{
Label1.Text = "Page Refreshed";
}
}
protected void Page_PreRender(object sender, EventArgs e)
{
ViewState["CheckRefresh"] = Session["CheckRefresh"];
}
}

Saturday, December 22, 2012

Code for update panel postback problem solving by using Jquery


 I have a grid when I postback this grid by linkbutton which is in this grid jquery function was not working in mouse over so I paste this code into update panel to avoid postback .

    script type ="text/javascript"
                var prm = Sys.WebForms.PageRequestManager.getInstance();
                prm.add_endRequest(function () {
                    grid();
                });
            script