2016-11-24 70 views
-1

我想使用MVC,Jquery將列表導出爲CSV文件。我想寫一個文件到響應流但是什麼都不做。沒有下載顯示。在mvc導出爲CSV不起作用

下面是我在.cshtml

<button id="btnGenerateCSV">Generate CSV</button> 

代碼的.js

$('#btnGenerateCSV').click(function() { 
    $.post(root + "ClaimInternal/DownloadCsv"); 
}); 

在myController的

  private string GetCsvString(IList<Area> Area) 
     { 
      StringBuilder csv = new StringBuilder(); 

      csv.AppendLine("AreaID,AliasName,Description,BankName"); 

      foreach (Area area in Area) 
      { 
       csv.Append(area.AreaID + ","); 
       csv.Append(area.AliasName + ","); 
       csv.Append(area.Description + ","); 
       csv.Append(area.BankName + ","); 

       csv.AppendLine(); 
      } 

      return csv.ToString(); 
     } 


     public void DownloadCsv() 
     { 
      using (Database db = new Database(_ConnectionString)) 
      { 
       AreaDAC dacArea = new AreaDAC(db); 
       List<Area> data = dacArea.Search("", "", ""); 
       string facsCsv = GetCsvString(data); 

       // Return the file content with response body. 
       Response.ContentType = "text/csv"; 
       Response.AddHeader("Content-Disposition", "attachment;filename=Area.csv"); 
       Response.Write(facsCsv); 
       Response.End(); 
       } 
     } 

我儘量讓這樣也

 public FileContentResult DownloadCsv() 
     { 
      using (Database db = new Database(_ConnectionString)) 
      { 
       AreaDAC dacArea = new AreaDAC(db); 
       List<Area> data = dacArea.Search("", "", ""); 

       JsonResult result = new JsonResult(); 
       result.JsonRequestBehavior = JsonRequestBehavior.AllowGet; 
       result.Data = data; 

       string facsCsv = GetCsvString(data); 
       return File(new System.Text.UTF8Encoding().GetBytes(facsCsv), "text/csv", "Area.csv"); 
      } 
     } 

我也做這樣的

  public void DownloadCsv() 
      { 
       using (Database db = new Database(_ConnectionString)) 
       { 
        AreaDAC dacArea = new AreaDAC(db); 
        List<Area> data = dacArea.Search("", "", ""); 
        string facsCsv = GetCsvString(data); 

        // Return the file content with response body. 
            Response.Clear(); 
       Response.Buffer = true; 
       Response.AddHeader("content-disposition", "attachment;filename=Area.csv"); 
       Response.Charset = ""; 
       Response.ContentType = "application/text"; 
       Response.Output.Write(facsCsv); 
       Response.Flush(); 
       Response.End(); 
        } 
      } 

但還是不行。沒有下載CSV出現。而當我得到了這一切工作,沒有錯誤。

回答

1

現在我已經得到了答案。我改變這樣的腳本,它的工作..

var cd = new System.Net.Mime.ContentDisposition 
       { 
        FileName = "Area.csv", 
        Inline = true, 
       }; 
       Response.AppendHeader("Content-Disposition", cd.ToString()); 
       return File(new System.Text.UTF8Encoding().GetBytes(facsCsv), "text/csv"); 

這是通過添加新System.Net.Mime.ContentDisposition工作。但我仍然不明白爲什麼。