c# - How to prevent postback when button is clicked -
i have code save file in database. have function in 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 file attach.\""; } } and here's html:
<asp:button id="btnattached" runat="server" text="attach file" onclick="attachfile" /> <asp:fileupload id="txtfile" size="46" runat="server" /> by clicking "attach file" button, call code behind function , save file browse user. work fine when refresh page goes function again , repeat saving process ending duplicate of records. how can avoid happend?
some tried are:
- adding
if (!ispostback) {}condition. - adding
onclientclick="return false"attribute in button.
but did not solve problem. thank in advance.
use technique prevent double trigger on control events after refreshing:
add code code behind page
prerendereventprotected void page_prerender(object sender, eventargs e) { viewstate["checkrefresh"] = session["checkrefresh"]; }add line on
page_loadevent.protected void page_load(object sender, eventargs e) { if (!ispostback) { session["checkrefresh"] = server.urldecode(system.datetime.now.tostring()); // rest of code here ... } }on controls event, button click or other control want prevent on page refresh check these condition first.
protected void attachfile(object sender, eventargs e) { if (session["checkrefresh"].tostring() == viewstate["checkrefresh"].tostring()) { // code starts here .. if (txtfile.hasfile) { //... } // code ends here .. session["checkrefresh"] = server.urldecode(system.datetime.now.tostring()); } }
cheers
Comments
Post a Comment