【问题标题】:C# - What is the difference of a Web method and a normal method. Why my block of code works in a normal method and not in a web methodC# - Web 方法和普通方法有什么区别。为什么我的代码块以普通方法而不是 Web 方法工作
【发布时间】:2014-11-18 05:45:37
【问题描述】:

谁能帮帮我,

我正在尝试导出到 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# jquery .net webmethod


【解决方案1】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-16
    • 2019-01-13
    • 2013-04-01
    • 1970-01-01
    • 2013-01-25
    • 2010-09-18
    相关资源
    最近更新 更多