3

I am new to ASP/C# programming:

I have an asp:button created as follows:

<asp:button
    ID="CreateItem"
    ClientIDMode="Static"
    OnClick="btnSave_Click"
    runat="server"
    Text="SAVE">
</asp:button>

In the code behind, I have the following:

btnSave_Click(object sender, EventArgs e)
{
    //Code here to create an Item    
}

I noticed that when I refresh the page after clicking my button, this function is being called. To verify, I ran the debugger and set a breakpoint inside the btnSave_Click function and verified that it was indeed going inside the function when I refresh my page. What am I doing wrong?

Rhs
  • 3,188
  • 12
  • 46
  • 84
  • 2
    Do you refresh after clicking the button? – Oded Dec 26 '12 at 19:59
  • @Oded yes. I was just about to edit that into my post – Rhs Dec 26 '12 at 19:59
  • That's why. The browser is trying to recreate the same request, so the server understands it to be a request that triggers the button click. You need to go to the address bar and press enter for a new request to be made. – Oded Dec 26 '12 at 20:01
  • Does this occur on the very first load of the page, or only when pressing refresh? – Scott Scowden Dec 26 '12 at 20:02
  • Is `btnSave_Click` being referenced anywhere else in your code behind? Perhaps in the `Page_Load`? – Colin Pear Dec 26 '12 at 20:02
  • @Oded is there a way to clear the request when the user refreshes or is this a non-issue? – Rhs Dec 26 '12 at 20:03
  • 2
    It can't be done on the browser. The normal way to deal with this is the [PRG pattern](http://en.wikipedia.org/wiki/Post/Redirect/Get) (user posts, server redirects (after processing) to a different page that the browser then gets)t – Oded Dec 26 '12 at 20:05

2 Answers2

6

It's being called on a page refresh after you clicked the button because the original button click caused the form to be posted. When you refresh the page after that, the browser is simply re-posting the form data and thus calling the call-back function again.

To avoid this you can simply enter the url or highlight the url in the address bar and press enter and it will treat it as a page load.

EDIT: Didn't fully understand what you were asking. To avoid having this happen when a user clicks refresh you can do as Oded mentioned in the comments and do a re-direct after posting: Post-Redirect-Get with ASP.NET

From the link:

protected void SaveClicked(object sender, EventArgs e)
{
    //save changes to database here

    //Redirect if all went well
    Response.Redirect("~/yourpage.aspx");
}
Community
  • 1
  • 1
CAbbott
  • 8,078
  • 4
  • 31
  • 38
0

You have to use PRG patern to avoid this problem. When you refresh the page your last request(either get or Post) resubmitted to the server again.

Solution: In the click event use Response.Redirect after your code

btnSave_Click(object sender, EventArgs e)
{
    //Code here to create an Item   
    Response.Redirect(@"~\page.aspx"); 
}
syed mohsin
  • 2,948
  • 2
  • 23
  • 47