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:
- Adding
if (!IsPostBack) {}
condition. - Adding
onClientClick="return false"
attribute in my button.
But it did not solve the problem. Thank you in advance.