4

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?

4
  • Open the developer tools of the browser and see how the request is being formatted. What does that JSON look like? Commented Jan 30, 2018 at 13:54
  • @GabrielLuci something looklike this: {filters:["1","2","3","4","5","6","7"]} Commented Jan 30, 2018 at 14:27
  • Try putting [FromBody] in front of string[] filters Commented Jan 30, 2018 at 14:31
  • @GabrielLuci when change it to "public JsonResult ShowReport([FromBody]string[] filters)", fillters set to null insted of string[0]! Commented Jan 30, 2018 at 14:34

3 Answers 3

5

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].

Sign up to request clarification or add additional context in comments.

Comments

2

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 :-)

5 Comments

This line was not commented in my code! Somehow i tries your method and use data : data, and [FromBody] but it`s not works also :(
I meant the comment under your post ;-) Anyway, do you get any response or any message from the failure or error handler?
There is no failure message just send something looks like this in Request Body: undefined=&undefined=&undefined=&undefined=&undefined=&undefined=&undefined=
This is my request headers if you may need: Host: localhost:51519 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:58.0) Gecko/20100101 Firefox/58.0 Accept: application/json, text/javascript, /; q=0.01 Accept-Language: en-US,en;q=0.5 Accept-Encoding: gzip, deflate Referer: localhost:51519/Report/ShowReport/13 Content-Type: application/json; charset=utf-8 X-Requested-With: XMLHttpRequest Content-Length: 76 Cookie: _ga=GA1.1.949841155.1515651415; .AspNetCore.Session=somecode Connection: keep-alive
try data: JSON.stringify(data),
1

I'm typing from mobile in the gym, so sorry for typos and poor syntax. I usually like to strongly type the input parameters of a controller. So instead of string [] filters you could have FilterList filters where FilterList is defined for example as

public FilterList { public List<string> filters {get; set;} }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.