我試圖做一些看起來應該很容易的事情,但我是新來的MVC和基於約定的編程。如何將JavaScript數組發佈到MVC 3控制器操作(由於文件下載而沒有AJAX)?
我有一個jQuery數據表,通過AJAX獲取PDF文檔的行。在fnRowCallback
中,我添加了複選框,以便用戶可以選擇多個文檔進行組合以進行單個下載。當複選框被選中時,文檔ID將被添加到JavaScript數組中,並且文件名將被添加到另一個數組中,以便在組合時可以將它們用於生成的PDF中的書籤。有沒有辦法將這兩個變量發送給控制器操作?到目前爲止,我所能做到的只有JSON.stringify()
其中一個變量,並使用隱藏字段將其發送給控制器,然後將其放入視圖中並將其反序列化到控制器中,但當我嘗試添加第二個變量。必須有一種更簡單的方法,但我甚至無法弄清楚這些令人費解的方式,並且我讀過的所有文章都使用AJAX。不過,我不能使用AJAX,因爲您無法在響應中發回二進制文件。
的JavaScript:
var aiSelectedPDFs = new Array();
var aiSelectedDocumentIDs = new Array();
$('#imgDownload').click(function() {
$('#selectedPDFs').val(JSON.stringify(aiSelectedPDFs));
$('#selectedDocumentIDs').val(JSON.stringify(aiSelectedDocumentIDs));
$('#DownloadSelectedPdfs').submit();
});
檢視:
<img id="imgDownload" src="@(Url.RootUrl())Content/images/icons/pdf.gif"
alt="Download selected documents" title="Download selected documents" />
@using (Html.BeginForm("DownloadSelectedPdfs", "Controller", FormMethod.Post,
new { id = "DownloadSelectedPdfs" }))
{
<input type="hidden" id="selectedPdfs" name="jsonSelectedPdfs"/>
<input type="hidden" id="selectedDocumentIDs" name="jsonSelectedDocumentIDs"/>
}
控制器:
[HttpPost]
public ActionResult DownloadSelectedPdfs(string jsonSelectedDocumentIDs)
{
var selectedDocumentIDs = new JavaScriptSerializer().Deserialize<int[]>(
jsonSelectedDocumentIDs);
var invoices = new Dictionary<string, byte[]>();
foreach (int documentID in selectedDocumentIDs)
{
invoices.Add(documentID.ToString(),
_documentService.GetDocument(documentID));
}
return new FileContentResult(PdfMerger.MergeFiles(invoices),
"application/pdf");
}
這90%是正確的。我發佈了修正,使其工作100%。我應該把你的標記作爲答案還是我的?我對StackOverflow真的很陌生,正如你可以看到我的名聲,所以我很樂意在這個問題上遵從你的判斷和道德。 –