2013-12-18 35 views
0

我有一點工作得很好的ajax。它發佈到一個返回文件的C#控制器。不幸的是,我認爲Ajax無法初始化文件下載。我真的需要發佈JSON。 JSON包含由用戶應用於表的過濾器。我曾嘗試將JSON作爲來自輸入的字符串發佈,但它不起作用,並且永遠不會填充我的對象。我意識到我的C#代碼下面什麼也沒做,但是返回一個文件,但是我可以在簡單的文件下載工作後添加更多的代碼。使用Ajax啓動文件下載或發佈JSON而不使用Ajax

的Javascript:

$.ajax(
    data: JSON.stringify(model), 
    contentType: 'application/json', 
    type: 'POST', 
    url: 'Respondents/DownloadCSV', 
    success: function() { alert('success'); }, 
    error: function() { alert('unsuccessful'); } 
}); 

C#

[HttpPost] 
public ActionResult DownloadCSV(RespondentViewModel model) 
{ 
    string csv = "Name, Source, Email, City, State, Gender, Ethnicity, Age, Last Edit, Owner, Group, Status Date, Status"; 
    return File(new System.Text.UTF8Encoding().GetBytes(csv), "text/csv", "DispositionReport.csv"); 
} 

回答

0

解決的辦法是:用url屬性

返回JSON對象

{ redirect_url: '/blabla/path/to/file/download' } 

製作重定向到通過的javascrip這個網址T,Ajax的成功

$.ajax(
    data: JSON.stringify(model), 
    contentType: 'application/json', 
    type: 'POST', 
    url: 'Respondents/GetJsonResult', // !!! 
    success: function (result) { 
      if (result.redirect_url) { 
       window.location = result.redirect_url; 
      } 
     }, 
    error: function() { alert('unsuccessful'); } 
}); 
+0

我沒有將這個文件存儲在服務器上。 – allencoded

+0

@allencoded,沒關係。您可以根據需要構建自己的網址。您可以使用「get」參數返回該網址。 –

1

我認爲這個問題是網址,例如以下更改:

url: '/Respondents/DownloadCSV',