Search code examples
c#asp.netexcelpostbackresponse

ASP.NET. HTML button causes a postback after exporting Excel file


I have both asp.net server button controls and html buttons in my asp.net web form.

<asp:LinkButton runat="server" ID="btnExportToExcel" OnClick="btnExportToExcel_Click">Excel</asp:LinkButton>
<button type="submit" class="btn btn-info btn-block">Refresh</button>

I use asp.net button OnClick event to send back an Excel file. Below is the code:

 protected void btnExportToExcel_Click(object sender, EventArgs e)
 {
    Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    Response.AddHeader("content-disposition", "attachment;  filename=ExcelDemo.xlsx");
    Response.BinaryWrite(ExcelHelper.GetByteArray(datatable));
    Response.End();
 }

The export to Excel works perfectly fine, but after the export is done, all html buttons start to cause a postback with target id of the asp.net button control responsible for the Excel export, i.e. the OnClick event of btnExportToExcel button is fired again and I get the same Excel file exported again.

Am i doing something wrong with the responce in the OnClick event? Or am I missing something else?

NB. I can fix the problem by using just asp.net buttons, but I would like to understand the nature of the problem.

EDIT. After the reply from Igor, is it correct that the problem has nothing to do with the Response (i.e. I thought that the Response might be missing something) and it could be considered as an expected behavior and I need to be careful with the buttons I use?


Solution

  • This is what happens on your page:

    1. asp:LinkButton is clicked. On its client-side click it calls __doPostBack that sets hidden __EVENTTARGET input value to btnExportToExcel.

    2. The form is submitted to the server. Browser is waiting for the new content to arrive.

    3. The new content is a downloadable file, so the browser page is not cleared and stays what it was during the submit.

    4. Clicking on any button with type="submit" causes the form submission with __EVENTTARGET still having btnExportToExcel value.

    5. Server-side page interprets POST request with Request.Form["__EVENTTARGET"]="btnExportToExcel" as the click of btnExportToExcel.