简体   繁体   中英

How to prevent postback when button is clicked

I have a code that save file in database. I have this function in my code behind:

protected void AttachFile(object sender, EventArgs e)
    {
        if (txtFile.HasFile)
        {
            string filename = Path.GetFileName(txtFile.PostedFile.FileName);
            string contentType = txtFile.PostedFile.ContentType;

            using (Stream fs = txtFile.PostedFile.InputStream)
            {
                using (BinaryReader br = new BinaryReader(fs))
                {
                    Random ran = new Random();

                    byte[] bytes = br.ReadBytes((Int32)fs.Length);
                    NewRequestService newrequest = new NewRequestService();

                    string temp_id = "";
                    temp_id = ran.Next(100000, 999999).ToString();

                    saveAttachFile(filename, contentType, bytes, temp_id);
                    hdnAttachID.Value = temp_id;
                    lblAttach.InnerHtml = msg;
                }
            }

        }
        else { lblAttach.InnerHtml = "\"Please browse the file to attach.\""; }

    }

And here's my HTML:

<asp:Button ID="btnAttached" runat="server" Text="Attach File" OnClick="AttachFile" />
<asp:FileUpload ID="txtFile" size="46" runat="server" />

By simply clicking "Attach File" button, it will call the code behind function and save the file browse by the user. It work just fine but when I refresh the page it goes to the function again and repeat the saving process ending with duplicate of records. How can I avoid this to happend?

Some I tried are:

  1. Adding if (!IsPostBack) {} condition.
  2. Adding onClientClick="return false" attribute in my button.

But it did not solve the problem. Thank you in advance.

Use this technique to prevent the double trigger on your control events after refreshing:

  1. Add this code to your code behind page PreRender event

     protected void Page_PreRender(object sender, EventArgs e) { ViewState["CheckRefresh"] = Session["CheckRefresh"]; } 
  2. Add this line on your Page_Load event.

     protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { Session["CheckRefresh"] = Server.UrlDecode(System.DateTime.Now.ToString()); // rest of your code here ... } } 
  3. On your controls event, like your button click or any other control that you want to prevent this on page refresh check these condition first.

     protected void AttachFile(object sender, EventArgs e) { if (Session["CheckRefresh"].ToString() == ViewState["CheckRefresh"].ToString()) { // your code starts here .. if (txtFile.HasFile) { //... } // your code ends here .. Session["CheckRefresh"] = Server.UrlDecode(System.DateTime.Now.ToString()); } } 

Cheers

You can use Post/Redirect/Get (PRG) pattern to overcome this. You can see a similar question answered here. how to prevent data from sending if user press F5 or refresh in asp.net?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM