0

I am trying to send two arrays of object as post request parameters.

POST request from front-end in .cshtml file

var PostFunctions = {
    PostTest: function () {
        const sampleIds = [1, 2, 3];
        const sampleStrings = ["1", "2", "3"];
        var data = {
            'sampleIds': sampleIds,
            'sampleStrings': sampleStrings
        };
        $.ajax({
            type: "POST",
            url: "/Home/GetSamplesNames",
            data: JSON.stringify(data),
            async: false,
            contentType: "application/json; charset=utf-8",
            success: function () {}
        });
    }
};

GetSamplesNames() code in controller

[HttpPost]
public JsonResult GetSamplesNames([FromBody] List<UInt32> sampleIds, [FromBody] List<String> sampleStrings)
{
    return new JsonResult(new List<String>() { "test" });
}

But in debug both parameters are null

enter image description here

What is my mistake with parameters stringify?.

Thank you in advance.

bairog
  • 3,143
  • 6
  • 36
  • 54
  • Hi, did you try to set the traditional property to true before making the get call ? [example](https://stackoverflow.com/questions/5489461/pass-array-to-mvc-action-via-ajax) – Eugene D May 21 '20 at 07:06
  • Try expecting a model with two lists not 2 lists appart – Flori Bruci May 21 '20 at 07:07
  • @EugeneD `traditional: true,` changes nothing :( – bairog May 21 '20 at 07:09
  • @FloriBruci Using a class with two lists works correctly. But I'm trying to make it working with two List parameters (as it's more clear to read and understand). Is it possible? – bairog May 21 '20 at 07:11
  • send them separately from AJAX: data : { _sampleIds: sampleIds, _sampleStrings: sampleStrings} Be aware of the "_" the _sampleStrings in my case is how they should be called in method – Flori Bruci May 21 '20 at 07:15

4 Answers4

1

For ASP.NET CORE applications, you will need to create a model that has the parameters you want to pass to the controller method.

For instance, List<UInt32> sampleIds, [FromBody] List<String> sampleStrings you would need to create a class such as:

public class SampleClass
{
    List<UInt32> SampleIds {get; set;}
    List<string> SampleStrings {get; set;}
}

and this would be your controller method declaration:

[HttpPost] // I don't think you need this
public JsonResult GetSamplesNames([FromBody] SampleClass params)

and then in you Javascript function you would do the following:

    // The names in this object have to be the same as the class created
    var params = {
        SampleIds = sampleIds,
        SampleStrings = sampleStrings
    };

    $.ajax({
        type: "POST",
        url: "/Home/GetSamplesNames",
        data: JSON.stringify(data),
        contentType: "application/json",
        success: function () {}
    });
JamesS
  • 2,167
  • 1
  • 11
  • 29
  • Thank you. I was aware of this method and it works for me. But I believed that there is a way to make it working with two List parameters (as it's more readable to my mind). Trying all solutions showed that it's impossible for ASP .NET Core – bairog May 21 '20 at 08:23
  • @bairog In ASP.NET-MVC you can yes, I don't believe it's possible with CORE however – JamesS May 21 '20 at 08:26
  • BTW: Looks like I really don't need `[HttpPost]` attribute. It is working correctly without it. – bairog May 21 '20 at 08:31
  • P.S. Where did you find info that `I don't believe it's possible with CORE`? Maybe some docs? Or it is based on you personal experience only? – bairog May 21 '20 at 08:33
  • @bairog Personal experience and docs. I've found/ read that you can pass a single string using the MVC way however multiple parameters or any other data type needs to be passed as an object. – JamesS May 21 '20 at 08:37
1

This works for me:

    [HttpPost]
    public JsonResult GetSamplesNames(List<uint> sampleIds, List<string> sampleStrings)
    {
        return new JsonResult(new List<String>() { "test" });
    }

<script type="text/javascript">

var PostTest = function () {
    var sampleIds = [1, 2, 3];
    var sampleStrings = ["1", "2", "3"];
    var data = {
        'sampleIds': sampleIds,
        'sampleStrings': sampleStrings
    };
    $.post('/Home/GetSamplesNames', $.param({ sampleIds: sampleIds, sampleStrings: sampleStrings}, true), function (data) { });
}

enter image description here

Eugene D
  • 347
  • 1
  • 3
  • 17
  • Hi again @bairog, try this. But as others told it's better to wrap up lists to object model and send the model instead. I use .NET Core 3.1 – Eugene D May 21 '20 at 08:30
  • Thank you. It is working for me also (.NET Core 3.1.4). BTW as [JamesS](https://stackoverflow.com/users/9177810/jamess) suggested `[HttpPost]` attribute is not required to work correctly. – bairog May 21 '20 at 08:38
  • @bairog, I'd say it's best practice to use attributes. Please take a look [Attributes](https://stackoverflow.com/questions/5332275/httppost-vs-httpget-attributes-in-mvc-why-use-httppost) – Eugene D May 21 '20 at 08:43
0

JSON stringify converts your object to a string, I don't think it complies to your controller parameters because you need 2 lists.

Try this instead;

var PostFunctions = {
    PostTest: function () {
        const ids = [1, 2, 3];
        const strings = ["1", "2", "3"];
        var passData = {
            sampleIds: ids,
            sampleStrings: strings
        };
        $.ajax({
            type: "POST",
            url: "/Home/GetSamplesNames",
            data: passData,
            async: false,
            contentType: "application/json; charset=utf-8",
            dataType: 'json', // since the server will return json object, you need to indicate dataType
            success: function (response) { alert(response); },
            error: function(err){ alert(err); },
        });
    }
};
Jerdine Sabio
  • 5,688
  • 2
  • 11
  • 23
  • Both parameters are still `null` :( – bairog May 21 '20 at 07:07
  • Oh I just read your comment, you're after an answer without the model parameter. – Jerdine Sabio May 21 '20 at 07:33
  • @bairog I've seen an answer that uses your format (JSON.Stringify). The difference is they used `traditional:true` property. https://stackoverflow.com/questions/26931042/how-to-pass-list-string-from-view-to-controller-by-ajax-jquery – Jerdine Sabio May 21 '20 at 07:51
  • That would work for ASP.NET-MVC but I don't believe it will work for ASP.NET Core – JamesS May 21 '20 at 07:59
0

Try this:

var PostFunctions = {
        PostTest: function () {
            const _sampleIds = [1, 2, 3];
            const _sampleStrings = ["1", "2", "3"];

            $.ajax({
                type: "POST",
                url: "/Home/GetSamplesNames",
                data: {sampleIds : _sampleIds, sampleStrings : _sampleStrings},
                async: false,
                contentType: "application/json; charset=utf-8",
                success: function () {}
            });
        }
    };

And in you controller :

[HttpPost]
public JsonResult GetSamplesNames(List<UInt32> sampleIds,List<String> sampleStrings)
{
    return new JsonResult(new List<String>() { "test" });
}
Flori Bruci
  • 436
  • 4
  • 11