如何在ASP.NET中的客户端保存LinqToCSV的输出

时间:2014-09-16 03:55:39

标签: c# asp.net linqtocsv

我目前能够将List保存到服务器上的CSV文件,如下面的代码所示。但是,我希望ASP.NET应用程序使用“文件保存”对话框提示用户并将其保存在其客户端系统中。所以我在“导出到CSV'按钮单击将列表绑定到GridView的页面。但是,此代码在IE中在运行时抛出JavaScript错误,复制如下。这有什么问题?响应应该在单独的ASPX上吗?

 CsvContext cc = new CsvContext();
            string outputFileName = string.Format("D:\\Dashboard.csv", DateTime.Now);
            cc.Write(filteredListOfPerformanceDashboardSummary, outputFileName);
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.ClearHeaders();
            HttpContext.Current.Response.ClearContent();
            HttpContext.Current.Response.AddHeader("content-disposition", outputFileName);
            HttpContext.Current.Response.ContentType = "text/csv";
            HttpContext.Current.Response.AddHeader("Pragma", "public");
            HttpContext.Current.Response.Write(cc.ToString());
            HttpContext.Current.Response.End();

我收到此IE错误

Error: Sys.WebForms.PageRequestManagerParserErrorException: The message received from the server could not be parsed

当我点击链接时,它会在此处显示错误

function Sys$WebForms$PageRequestManager$_endPostBack(error, executor, data) {
        if (this._request === executor.get_webRequest()) {
            this._processingRequest = false;
            this._additionalInput = null;
            this._request = null;
        }
        var handler = this._get_eventHandlerList().getHandler("endRequest");
        var errorHandled = false;
        if (handler) {
            var eventArgs = new Sys.WebForms.EndRequestEventArgs(error, data ? data.dataItems : {}, executor);
            handler(this, eventArgs);
            errorHandled = eventArgs.get_errorHandled();
        }
        if (error && !errorHandled) {
            throw error;
        }
    }

1 个答案:

答案 0 :(得分:1)

您可以使用Responce.WriteFile

CsvContext cc = new CsvContext();
string outputFileName = string.Format("D:\\Dashboard.csv", DateTime.Now);
cc.Write(categoryList, outputFileName);  
Response.Clear();
Response.ContentType = "text/csv"; //or "application/csv" 
Response.AddHeader("Content-disposition", "attachment; filename=\"sample.csv" + "\"");
Response.WriteFile(outputFileName);
Response.Flush();
Response.End();