C# - Web 方法和普通方法有什么区别.为什么我的代码块在普通方法中工作,而不是在 Web 方法中工作

本文关键字:方法 工作 Web 为什么 什么 区别 我的 代码 | 更新日期: 2023-09-27 18:30:48

有人可以帮我吗,

我正在尝试导出到 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();

为了与我的问题相关,当我将此代码块放入 jQuery 通过 Ajax 调用的 WebMethod 时,它只是返回要在消息弹出窗口中导出的字符串,而当我将此代码块放入 ASP 按钮控件的单击方法(例如 ExcelExportButton_Click)时,它可以工作。

不工作代码:

[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();
    }

工作代码:

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();
    }

请不要介意示例字符串。

C# - Web 方法和普通方法有什么区别.为什么我的代码块在普通方法中工作,而不是在 Web 方法中工作

通过 AJAX 调用 Web 方法不会触发文件下载框。您有以下几种选择:

你可以使用JQuery插件(https://stackoverflow.com/a/9970672/94853)。这将创建最接近您要实现的体验。

或者,您可以简单地将 window.location 更改为 Web 方法 (https://stackoverflow.com/a/7660817/94853) 的 URL。根据您从 JavaScript 传递 ExcelReport 字符串的方式,这可能是也可能不是更简单的路由。