I`ve wrote this ajax function:
$(function () {
$("#showReport").click(function () {
var data = [];
for (var i = 0; i <@Model.LiFilters.Count;i++) {
data[i] = $("#filter" + i).val();
$("#myDiv").html("Hello!");
}
alert('{filters:' + JSON.stringify(data) + '}');
$("#myDiv").remove();
$.ajax({
type: "POST",
url: '@Url.Action("ShowReport", "Report")',
traditional: true,
//data: '{filters:' + JSON.stringify(data) + '}',
data: { filters : data },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
alert(data);
alert(response[0]);
$("#myDiv").html(response[0]);
alert(response);
},
failure: function (response) {
alert(response.responseText);
},
error: function (response) {
alert(response.responseText);
}
});
return false;
});
});
And have this action in Report controller:
[HttpPost]
public JsonResult ShowReport(string[] filters)
{
C_AminReport aminReport = null;
string sErr = string.Empty;
//C_ReportParams aminParams = null;
//C_AminReport aminReport;
string sReport = "Empty Report!";
if (C_AminReport.U_GetReport(aminReport.ID, out aminReport))
{
int iConIndex = Get_ServiceIndex();
aminReport.U_RenderReport(iConIndex, ref sErr);
aminReport.U_GetReportFromAmin(iConIndex, aminReport, out sReport, ref sErr);
}
string[] asReport;
JsonBuilder.U_TryReadJson(sReport, out asReport);
return Json(asReport);
}
But when run code i see data array filled but inside of the ShowReport action, fillters array is an empty array and not filled! I also tries [FromBody] tag inside action params but it not works to! What is the problem?
I tested your JavaScript and it's trying to send all the data in the query string.
You have to use JSON.stringify
. One of these should work:
data: '{filters:' + JSON.stringify(data) + '}'
or
data: JSON.stringify(data)
I suspect it's the second that will work.
You may still need [FromBody]
.
you don't send an array, but an object with a property 'filters' that is an array.
{filters:["1","2","3","4","5","6","7"]}
As you pointed out in the comment :)
Try to send the array directly:
$.ajax({
type: "POST",
url: '@Url.Action("ShowReport", "Report")',
traditional: true,
//data: '{filters:' + JSON.stringify(data) + '}',
data: data, // <=== !!
contentType: "application/json; charset=utf-8",
Adding the attribute [FromBody] is also not a bad idea :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With