使用ASP .NET MVC和jQuery AJAX请求下载服务器生成的CSV [英] Download server generated CSV with ASP .NET MVC and jQuery AJAX request

查看:383
本文介绍了使用ASP .NET MVC和jQuery AJAX请求下载服务器生成的CSV的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理以 CSV 格式导出数据的机制。
我使用 jQuery JSON 格式发送数据:

  var data = JSON.stringify(dataToSend); 
$ .post('DumpToCSV',{'data':data});

然后在控制器中生成 CSV 文件:

  public ActionResult DumpToCSV(string data)
{
Response.Clear();

XmlNode xml = JsonConvert.DeserializeXmlNode({records:{record:+ data +}});

XmlDocument xmldoc = new XmlDocument();
//创建XmlDoc对象
xmldoc.LoadXml(xml.InnerXml);
//创建XML Steam
var xmlReader = new XmlNodeReader(xmldoc);
DataSet dataSet = new DataSet();
//使用Xml加载数据集
dataSet.ReadXml(xmlReader);
//在数据集内返回单个表
var csv = CustomReportBusinessModel.ToCSV(dataSet.Tables [0],,);

HttpContext context = System.Web.HttpContext.Current;
context.Response.Write(csv);
context.Response.ContentType =text / csv;
context.Response.AddHeader(Content-Disposition,attachment; filename = Custom Report.csv);
Response.End();
return null;
}

它会返回 CSV


这个主题的区别:
在MVC中查看/下载文件
是我使用AJAX请求



解决方案

如果您想根据一些数据下载文件,它最好不要使用Ajax,因为它真的很难通过Ajax处理文件。其中一个可行的解决方案是添加指向其他库的链接





javaScript 代码中:

  var urlParams = $ .param(dataToSend); 
window.location.href =DumpToCSV+ urlParams;

这样你的所有数据序列化为url字符串,通过Ajax获取文件没有问题。 / p>

然后在 Controller 中,最好返回 FileContentResult 甚至 FileStreamResult 如果你有真正的大文件。此外,你的模型进入yout控制器可以强类型和MVC ModelBuilder 轻松地映射它从url字符串。所以yout数据对象可以是c#类,像这样:

  public class CSVData 
{
public string Name {get;组; }
public int Count {get;组; }
public int SomeId {get;组; }
}

并且你不需要在Controller中去除数据。查看更多资讯这里

  public FileContentResult DumpToCSV(CSVData data)
{
XmlNode xml = data.ToXmlNode();

XmlDocument xmldoc = new XmlDocument();
//创建XmlDoc对象
xmldoc.LoadXml(xml.InnerXml);
//创建XML Steam
var xmlReader = new XmlNodeReader(xmldoc);
DataSet dataSet = new DataSet();
//使用Xml加载数据集
dataSet.ReadXml(xmlReader);
//在数据集内返回单个表
var csv = CustomReportBusinessModel.ToCSV(dataSet.Tables [0],,);

return File(new System.Text.UTF8Encoding()。GetBytes(csv),text / csv,Custom Report.csv);
}

正如你所看到的那样,不需要使用 HttpContext 在MVC中你可以做更清洁和明显的方式。



PS。如果你的 csv 对象只是一个 byte [] ,那么你可以这样写:

  return File(csv,text / csv,Custom Report.csv); 


I am working on mechanism to export data in CSV format. I am sending data in JSON format using jQuery :

var data = JSON.stringify(dataToSend);
 $.post('DumpToCSV', { 'data': data });

Then in the controller I am generating a CSV file :

 public ActionResult  DumpToCSV(string data)
    {
        Response.Clear();

        XmlNode xml = JsonConvert.DeserializeXmlNode("{records:{record:" + data + "}}");

        XmlDocument xmldoc = new XmlDocument();
        //Create XmlDoc Object
        xmldoc.LoadXml(xml.InnerXml);
        //Create XML Steam 
        var xmlReader = new XmlNodeReader(xmldoc);
        DataSet dataSet = new DataSet();
        //Load Dataset with Xml
        dataSet.ReadXml(xmlReader);
        //return single table inside of dataset
        var csv = CustomReportBusinessModel.ToCSV(dataSet.Tables[0], ",");

        HttpContext context = System.Web.HttpContext.Current;
        context.Response.Write(csv);
        context.Response.ContentType = "text/csv";
        context.Response.AddHeader("Content-Disposition", "attachment;filename=Custom Report.csv");
        Response.End();
        return null;
    }

It returns back the CSV in response, but how do I tell the browser to donwload it?

The difference between this topic : Returning a file to View/Download in MVC Is that I'm using AJAX request

解决方案

If you want to download file based on some data that you can post to Controller it's better not use Ajax, becouse it's really hard to deal with files via Ajax. One of posible solutions is to add link to additional library.

What i whould like to advice you is to use simple GET request:

In your javaScript code:

var urlParams = $.param(dataToSend);
window.location.href = "DumpToCSV"+ urlParams;

This way you serialize all your data to url string and have no problem with getting file via Ajax.

Then in your Controller it's better to return FileContentResult or even FileStreamResult if you have really big files. Also, your model that go into yout controller can be strongly typed and MVC ModelBuilder Map it from url string easily. So yout data object can be c# class like this:

public class CSVData
{
   public string Name { get; set; }
   public int Count { get; set; }
   public int SomeId { get; set; }
}

And you don't need to desirialize your data in Controller at all. See more info here.

public FileContentResult DumpToCSV(CSVData data)
{
    XmlNode xml = data.ToXmlNode();

    XmlDocument xmldoc = new XmlDocument();
    //Create XmlDoc Object
    xmldoc.LoadXml(xml.InnerXml);
    //Create XML Steam 
    var xmlReader = new XmlNodeReader(xmldoc);
    DataSet dataSet = new DataSet();
    //Load Dataset with Xml
    dataSet.ReadXml(xmlReader);
    //return single table inside of dataset
    var csv = CustomReportBusinessModel.ToCSV(dataSet.Tables[0], ",");

    return File(new System.Text.UTF8Encoding().GetBytes(csv), "text/csv", "Custom Report.csv");
}

As you can see the is no need to work with HttpContext in MVC in your case you can do it much cleanier and obvious way.

PS. If your csv object is just a byte[] then you can write like this:

    return File(csv, "text/csv", "Custom Report.csv");

这篇关于使用ASP .NET MVC和jQuery AJAX请求下载服务器生成的CSV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆