0

I have 2 textbox on my page and a Button. When I click on a button, the text from the textbox is emailed. But, then when i refresh the page and no content is there, then also i get an email.

protected void Button1_Click(object sender, EventArgs e)
{
    if (!string.IsNullOrEmpty(TextBox1.Text) && !string.IsNullOrEmpty(TextBox2.Text))
    {
           //email logic
           TextBox1.Text = "";
           TextBox2.Text = "";

    }

    else
    {
    //do nothing
    }
 }

Here, on clicking the button, i get an email but then when i refresh the page, even though there is no data, then also it goes inside the loop and i get an email.

How do i stop this ?

user1989
  • 217
  • 2
  • 13
  • Post data are part of request, all values are stored in it and after you hit F5, you are resending request not creating new one. That is a reason why you are getting new email. – TheLittleHawk Dec 01 '14 at 01:12
  • possible duplicate of [Post-Redirect-Get with ASP.NET](http://stackoverflow.com/questions/5381162/post-redirect-get-with-asp-net) – Win Dec 01 '14 at 01:20
  • You may disable ViewState in your page directive. – andrey.shedko Dec 01 '14 at 02:30

2 Answers2

1

Do the following in your Page_Load event and keep your TextBoxes and Button in an <asp:UpdatePanel>. Then the page will not ask to re-submit each time you refresh the page.

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        TextBox1.Text = string.Empty;
        TextBox2.Text = string.Empty;
    }
}

UPDATE

Keep the controls within an UpdatePanel as follows

<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" >
<ContentTemplate>
    <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
    <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" Text="Send mail" onclick="Button1_Click" />            
</ContentTemplate>
</asp:UpdatePanel> 
Sam
  • 2,917
  • 1
  • 15
  • 28
  • what do you mean by keeping in ?? – user1989 Dec 01 '14 at 02:11
  • Sorry, keep your controls in an UpdatePanel – Sam Dec 01 '14 at 02:14
  • Awesome, it worked. But can you explain me why it worked, when i kept the control in update panel ? – user1989 Dec 01 '14 at 03:27
  • 1
    Because it's using Ajax and does a partial update. And, Script manager takes care of the page refresh issue you faced before. It only submits the form once how many time you refresh the page. – Sam Dec 01 '14 at 03:30
0

You need to use the the POST > Redirect > GET pattern. Here is explanation link

Community
  • 1
  • 1
TheLittleHawk
  • 628
  • 3
  • 22