Thursday, January 28, 2010

ASP.NET C# Refresh page from code behind

To refresh your page you may use the javascript function:


window.location.reload();


For example you can use that on the OnClientClick attribute of an ASP.NET button:


<asp:button ID="btnRefresh" OnClick="btnRefresh_Click" runat="server" Text="REFRESH" 
OnClientClick="window.location.reload();" />


The code above will work fine, but if let's say you have some other server-side logic you want to run on the code for btnRefresh_Click, it won't be executed because the page would already be refreshed by then.


So to run your server-side code, first remove the OnClientClick attribute on the asp button tag above. Then place the following code inside your button click event:



protected void btnRefresh_Click(object sender, EventArgs e)
{
    //Your logic here...
    Page.Response.Redirect(HttpContext.Current.Request.Url.ToString(), true);
}


We simply redirect the page to its current url and that does the trick.



-k





17 comments:

  1. Nice post.
    Solved me one problem.

    Thanks.

    ReplyDelete
  2. Thanks!
    second option worked for me

    ReplyDelete
  3. thanks! solves my Prob!

    ReplyDelete
  4. Just what I was looking for. Worked great, thanks.

    ReplyDelete
  5. That wa great...Both worked for me!

    ReplyDelete
  6. süper bir kod. çok işime yaradı.

    ReplyDelete
  7. Thanks a lot. It is the best for me

    ReplyDelete
  8. some page refresh but some page don't refresh.why?

    ReplyDelete
  9. This was the perfect solution. I have been battling an issue with the .Net life cycle regarding:
    Pre-Render
    Page_Init
    Page_Load
    having these events occur before my button click event which was causing some data to not be refreshed in session states. This fixed my issue.
    Thanks.

    ReplyDelete
  10. on refresh i want to call code behind file on certain interval

    ReplyDelete
  11. I am extremely impressed along with your writing abilities, Thanks for this great share.

    ReplyDelete
  12. good Solution.. It's Working

    ReplyDelete
  13. Blogging is the new poetry. I find it wonderful and amazing in many ways.

    ReplyDelete
  14. Hey keep posting such good and meaningful articles.

    ReplyDelete
  15. Hey keep posting such good and meaningful articles.

    ReplyDelete