1

Can someone help me,

I'm trying to do an export to excel module and I have this code for he export:

HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=exportTest.xls");
        HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
        HttpContext.Current.Response.Output.Write(excelExport);
        HttpContext.Current.ApplicationInstance.CompleteRequest();

to relate to my question, when I put this block of code to a webmethod invoked by jquery through ajax, it just gives me back the string to export in a message popup, while when I put this block of code into a click method for an asp button control (e.g. ExcelExportButton_Click) it works.

Not working code:

[WebMethod]
    public static void ExportReportsTableToExcel(string ExportReport)
    {
        string excelExport = "a string to export to excel";
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=exportTest.xls");
        HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
        HttpContext.Current.Response.Output.Write(excelExport);
        HttpContext.Current.ApplicationInstance.CompleteRequest();
    }

Working code:

protected void ExportReportButton_Click(object sender, EventArgs e)
    {
        string excelExport = "a string to export to excel";
        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.AddHeader("content-disposition", "attachment; filename=exportTest.xls");
        HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
        HttpContext.Current.Response.Output.Write(excelExport);
        HttpContext.Current.ApplicationInstance.CompleteRequest();
    }

Please, don't mind the sample string.

eps
  • 21
  • 2
  • possible duplicate of [Difference between webservice, web methods & server side code?](http://stackoverflow.com/questions/3952400/difference-between-webservice-web-methods-server-side-code) – Chetan Sanghani Nov 18 '14 at 06:39
  • basically, I know the difference of webmethod and a normal method. I listed the cases that I have to explain further what I meant in the title. I apologize if the title is misleading. – eps Nov 18 '14 at 06:53

1 Answers1

1

Invoking the web method through AJAX won't trigger the file download box. You have a few options:

You could use a JQuery plugin (https://stackoverflow.com/a/9970672/94853). This will create the experience closest to what you are trying to achieve.

Alternatively, you could simply change the window.location to the URL of the web method (https://stackoverflow.com/a/7660817/94853). Depending on how you are passing the ExcelReport string from JavaScript, this may or may not be the simpler route.

Community
  • 1
  • 1
Loren Paulsen
  • 8,960
  • 1
  • 28
  • 38