2013-01-06 62 views
5

我正在通過以下代碼發送JSON對象。控制器返回CSV格式的值,應該提供打開或保存爲CSV文件的提示。我無法理解,準確的代碼應該是什麼樣的成功寫:函數(結果)如何處理.ajax post中的FileStream返回類型?

鏈接,出口

Html.ActionLink("Export", "", "", null, new { @onclick = "return exportData();"}) 

function exportData() { 

var searchViewModel = getExLogSearchModelData(); 
var path = getAbsolutePath("ExclusionLog", "ExportData"); 
$.ajax({ 
    url: path, 
    cache: false, 
    contentType: 'application/json; charset=utf-8', 
    dataType: 'html', 
    type: 'POST', 
    data: JSON.stringify(searchViewModel), 
    success: function (result) { 
    }, 
    error: function (error) { 
     $("#voidcontainer").html("Error"); 
    } 
}); 

}

控制器的ActionResult

public ActionResult ExportData(ExclusionLogSearchViewModel postSearchViewModel) 
    { 
     try 
     { 
      IEnumerable<ExclusionLogViewModel> exclusionLogData = null; 
      exclusionLogcData = this._workerService.GetExclusionLogData(postSearchViewModel); 

      return CSVFile(exclusionLogMembershipSyncData.GetStream<ExclusionLogViewModel>(), "ExclusionLogTables.Csv"); 
     } 
     catch (Exception ex) 
     { 
       throw ex; 
     } 
     return null; 
    } 

能否請您建議如何做到這一點?

回答

3

我已經打了同樣的問題,我沒有找到一種方法,使用$.ajax來下載文件,但我發現了一個優秀的JavaScript庫,提供了類似的行爲:

https://github.com/johnculviner/jquery.fileDownload

你只需要調用是這樣的:

$.fileDownload(path, { 
    httpMethod: 'POST', 
    data: JSON.stringify(searchViewModel), 
    success: function (result) { 
    }, 
    error: function (error) { 
     $("#voidcontainer").html("Error"); 
    } 
}); 

記住在控制器創建的cookie。在src/Common有適合你的動作過濾器。

相關問題