Actually you can pass JSON string from array with @Url.Action()
helper using query string parameter like this:
<script>
$(function() {
var id = "10";
var deptno = "C001";
var PdfInputs = [];
for (var i = 0; i < totalbol; i++)
{
PdfInputs.push({
firstName: "John",
lastName: "Doe",
age: 46
});
}
location.href = '@Url.Action("DoSomething", "Customer")?id=' + id + '&deptno=' + deptno + '&PdfInputs=' + JSON.stringify(PdfInputs);
})
</script>
However I strongly discourage this practice because passed JSON string may exceeds query string limit if the array has large amount of data. Additionally, you cannot use @Url.Action()
helper for action method marked with [HttpPost]
attribute (it only works for GET
method), hence I recommend to use jQuery.ajax()
to pass PdfInputs
array as List<PdfInputs>
& TempData
/Session
state variable to store file contents, then download PDF file using HttpGet
controller action as provided below:
jQuery
<script>
$(function() {
var id = "10";
var deptno = "C001";
var PdfInputs = [];
for (var i = 0; i < totalbol; i++)
{
PdfInputs.push({
firstName: "John",
lastName: "Doe",
age: 46
});
}
$('#buttonid').click(function () {
$.ajax({
type: 'POST',
url: '@Url.Action("DoSomething", "Customer")',
// traditional: true,
data: $.param({ id: id, deptno: deptno, pdfInputs: PdfInputs }, true),
success: function (result) {
location.href = '@Url.Action("Download", "ControllerName")?id=' + id;
},
error: function (err) {
// error handling
}
});
});
})
</script>
Controller (DoSomething Action)
[HttpPost]
public ActionResult DoSomething(string id, string deptno, List<PdfInputs> pdfInputs)
{
// Some magic code here...
// Save file to TempData or Session state
byte[] fileContent = fileStreamInstance.ToArray();
TempData["FileToDownload"] = fileContent;
return Json("Success");
}
Controller (Download Action)
[HttpGet]
public ActionResult Download(string id)
{
string fileName = "yourfilename.pdf";
// other code here
if (TempData["FileToDownload"] != null)
{
byte[] content = TempData["FileToDownload"] as byte[];
return File(content, "application/pdf", fileName);
}
else
{
return new EmptyResult();
}
}