Detecting ASP.NET (C#) Browser Refresh

Problem: Many times we come across the scenario where hitting the browser’s refresh button or pressing the F5 key performs exactly the same steps last performed by their .NET code. i.e. what ever there is in the last request made to the web site. For example, lets suppose on our page we have a button on click of which page is supposed to make an entry in the data base as per the input values entered on the page. Every time this button is pressed a new entry will be created in the database. But what if after pressing the button explicilty, next time user refreshes the page using F5 or refresh button of the browser? Answer is, the same data entry will be created in the data base again with the values entered previously. This is because, event handler for the button will be called again with the same request made earlier.

So basically, there should be some work arround from which we can detect whether the request made from the browser is the real request made through the button press & user really wants to make an entry in the database or the request just came beacuse user has refreshed the page/pressed F5.

Solution: If we are able to detect the source of the coming page-post request either on client side or on the server side we can make our logic and take appropriate actions, may be different on actual request and different on the request made by F5/page refresh.

Though on the server side it’s very hard to delect the source of the coming request, we can detect it using the form’s onsubmit event. This is the event raised only when the page is actually posted like on click of a button, and will not be called when page is refreshed.

Note: When we refresh the page after submitting the same, a prompt will be there with two options 1. Retry & 2. Cancel. If user selects ‘Retry’ then only page will go for refreshing, otherwise no action wil be taken.

So as I stated that OnSubmit event of the form can be used to detect the actual postback versus postback on refersh. We could think of a javascript in which OnSubmit event can be handled and a hidden variable can se set in case of actual/genuine postback and the same variable’s value could be used on the server side to take the necessary action. And at last this hidden variable must be reset to its initial value for the forthcoming request.

But one point here to be noted is, when we set/reset the hidden variable’s value after doing the required stuff on the actual click of the button, this reset value will not be available to the request when the page is immediately refreshed after the genuiine postback, because request still contains all the values for which it had been posted last time.

So to aviod this problem we need to use a static variable which must be set to the latest value of the hidden variable every time a genuine postback happens.

JavaScript used:

<script language=”javascript” type=”text/javascript”>

    function fun()

    {

        var hdn = this.document.getElementById(“<%=hdn.ClientID %>”);        

        hdn.value = hdn.value + “1”;

    }

</script>

<form id=”form1” runat=”serveronsubmit=”fun()”>

        <div>

            <asp:TextBox ID=”TextBox1” runat=”server“></asp:TextBox>

            <asp:Button ID=”Button1” runat=”server” Text=”Button” OnClick=”Button1_Click” />            

        <asp:HiddenField ID=”hdn” runat=”server” />        

        </div>

</form>

Server Side Code:

    static string done = “x”;

    static object objLock = new object();          //For thread safety

    protected void Page_Load(object sender, EventArgs e)

    {

    }

    protected void Button1_Click(object sender, EventArgs e)

    {

        //As static variables are not thread safe

        lock (objLock)

        {

            if (hdn.Value.ToString().Length > done.Length || done == “x”)

            {

                //Do work required in case of genuine postback

                done = hdn.Value;

            }

            else

            {

                //Postback on Refresh/F5

            }

        }

    }

As shown above, in case of genuine postback, onsubmit event will call fun() method and hidden variable will be incremented in length. On the server side its length will be compared to the static variable’s length and in this case length of value of hidden field will be greater. Now after doing the required stuff, static variable is set to the value of hidden field so that now they become equal and if next time genuine postback does not happen they will not allow to execute the If {} block.

Advertisements
This entry was posted in .Net 2.0. Bookmark the permalink.

25 Responses to Detecting ASP.NET (C#) Browser Refresh

  1. BizLead says:

    Munish, thanks for your tip, it was exactly what I was needed

  2. DAve says:

    Hello,

    How would you do this within the page onload when the page first loadeds

  3. Kaysar Ahmed says:

    thanks munish that a nice solution for me which i faced.

  4. Thanks for the comments, Kaysar.

  5. Sen says:

    Thanks Munish Bansal, I was in search of this.

  6. Thanks for your comments, Sen !

  7. Amar Kumar says:

    Hi Munish,

    Nice article.. I will look to implement this..

    I faced similar prob(pior to have look at the solution provided by you).. and came a/c the solution below..

    protected void Page_Load(object sender, EventArgs e)
    {
    if (!this.Page.IsPostBack)
    Session[“update”] = Server.UrlEncode(System.DateTime.Now.ToString());
    ……your code…………..

    }

    protected void Page_PreRender(object sender, EventArgs e)
    {
    ViewState[“update”] = Session[“update”];
    }
    protected void lnkAddProject_Click1(object sender, ImageClickEventArgs e)
    {
    if (ViewState[“update”].ToString() == Session[“update”].ToString())
    {
    ……….your code ——
    Session[“update”] = Server.UrlEncode(System.DateTime.Now.ToString());
    }

  8. Thanks for your comments, Amar !

    Munish Bansal

  9. vivek says:

    Hi Munish,
    I have tried your code bt it dont work
    why i wll give you the answer
    suppose, i have 2 monitors

    monitor/browser 1: click on button will changed the variable done “x” to 1

    monitor/browser 2: when click on button im nt able to go throught the if condition as value of variable done got changed to 1

    As static variable is accessible by all users with the updated value.

    Hi Amar ,
    ur code rocks man

  10. Umesh says:

    I have used master page and form tag is on master page
    but hidden filed in content page how should i call content page function on master page

  11. kathirvel says:

    hi i am working in timer control for resetting time. i want to update all the clients browser when any one client resets time. say machine a is scheduled and has a left with 10mins time but due to preemption another job j gets priority and and job A is scheduled to 50mins later. how can we do this in asp.net

  12. tom says:

    Hi,

    This is a good solution. I’m trying to do the same thing but in a Asp.Net Web Control. static variables don’t seem to work and anything in the view state gets blown away after a postback…any ideas?

    TIA…tom

  13. Hi Tom,

    If static variable is not working in case of a web control, you can try using Control State to maintain the state of the variable across posts.

    Hope this will resolve your problem.

    If I’ll find some other solution, will let you know.

    Thanks,
    Munish Bansal

  14. Charles says:

    nice one …

  15. Charles says:

    Although the static variable causes issues for multiple requests from different browsers

  16. Sailaja says:

    Really, you helped me a lot. It’s working.. I worked a lot to resolve this issue, and finally i found your blog.

    your solution is working for me. Thanks a lot…

    great post.

  17. Thanks for your comments, Sailaja.

  18. Anoop Sihag says:

    Nice post.

    But I have doubt on the comment given by you in your code snippet. You posted that a static variables are not thread safe.

    This is not true in case of Static variable. Because I read somewhere that ASP.NET has internal locking mechanism for static variable.

    Please let me know what do you on this.

  19. Ryan says:

    Hey Munish,

    A better way to handle this problem would involve overriding the page’s LoadViewState and SaveViewState. An example is found here: http://www.codeproject.com/kb/aspnet/Detecting_Refresh.aspx

    Anyway, keep up the good work!

    Ryan

  20. suresh says:

    Thanks dude!!!! its is working fine.

  21. katalog says:

    I’m truly enjoying the design and layout of your
    blog. It’s a very easy on the eyes which makes it much more enjoyable for me to
    come here and visit more often. Did you hire out a developer to create your theme?

    Excellent work!

  22. Tremendous issues here. I’m very satisfied to peer
    your post. Thank you so much and I’m looking forward to
    touch you. Will you please drop me a mail?

  23. Pingback: [RESOLVED]how to redirect to login page when we click refresh button or F5 button | ASP Questions & Answers

  24. Pingback: [RESOLVED]how to redirect to login page when we click refresh button or F5 button | ASP Web Form Data Control

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s