Wednesday, December 21, 2011

Prevent postback events on page refresh

A common concern of ASP.NET developers is, "How do I prevent previously submitted form data from being reinserted into the database when the user presses the browser's Refresh button?"

Different solutions are available for this problem.

  1. Reload the page after successful postback

    A simple solution is to Reload the same page using Response.Redirect after successful transaction.

    Response.Redirect(Request.Url.ToString(), false);

    A disadvantage of this approach is that page ViewSate will not be retained.


  2. Using OnClientClick event (javascript)

    Create a javascript function which validates the fields to be submitted. If any validation failed it has to return false otherwise it has to return true.

    To avoid the post back handle the OnClientClick event call the javascript function which retuns true on successful validation otherwise false. If OnClientClick gets true from the script function then it would raise the OnClick event, otherwise it would not.

    <asp:Button ID="btnValidate" runat="server" Text="Click Here!!" OnClientClick=" return ValidateEmail()" OnClick ="btnValidate_Click"/>

    Below is the sample javascript:

    function ValidateEmail()
    {
    var x = document.getElementById('txtemail');

    var val = x.value;
    if(val == "")
    {
    alert("Please enter your email id");
    x.focus();
    return false;
    }
    return true;
    }

    The fields should be cleared on successful completion of postback.


  3. Server-side code using Session and ViewState variables

    A simple way to implement refresh trapping is by the use of a date/time stamp held in a ViewState variable and a date/time stamp held in the user's Session. When the page is first loaded, a Session variable is populated with the current date/time. On the page's PreRender event, a ViewState variable is set to the value of the Session variable. These two values are compared to each other immediately before the database INSERT command is run.

    If they are equal, then the command is permitted to execute and the Session variable is updated with the current date/time, otherwise the command is bypassed. Should the user refresh the page, the ViewState variable will be repopulated from the post header, so then the ViewState and Session variables will no longer hold the same values, and the INSERT command will not run. Note that ViewState needs to be enabled on the page for this to work; if ViewState is not enabled then a hidden form field may be used instead.

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

    public void Page_PreRender(object sender, EventArgs e)
    {
    ViewState["update"] = Session["update"];
    }

    public void Button1_Click(object sender, EventArgs e)
    {
    if (Session["update"].ToString() == ViewState["update"].ToString()) {
    if (AddEmployee(firstName.Text, lastName.Text) == 0) {
    Message.Text = "Success";
    Session["update"] = Server.UrlEncode(System.DateTime.Now.ToString());
    } else {
    Message.Text = "Failure";
    }
    } else {
    Message.Text = "Failure - Session";
    }
    firstName.Text = "";
    lastName.Text = "";
    }

Happy coding…

No comments:

Post a Comment