Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing A List Of Objects Into An MVC Controller Method Using jQuery Ajax

People also ask

Can we implement AJAX using jQuery in MVC?

Using AJAX In ASP.NET MVC. Implementation of Ajax can be done in two way in ASP.Net Application: using Update Panel and, using jQuery.


Using NickW's suggestion, I was able to get this working using things = JSON.stringify({ 'things': things }); Here is the complete code.

$(document).ready(function () {
    var things = [
        { id: 1, color: 'yellow' },
        { id: 2, color: 'blue' },
        { id: 3, color: 'red' }
    ];      

    things = JSON.stringify({ 'things': things });

    $.ajax({
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        type: 'POST',
        url: '/Home/PassThings',
        data: things,
        success: function () {          
            $('#result').html('"PassThings()" successfully called.');
        },
        failure: function (response) {          
            $('#result').html(response);
        }
    }); 
});


public void PassThings(List<Thing> things)
{
    var t = things;
}

public class Thing
{
    public int Id { get; set; }
    public string Color { get; set; }
}

There are two things I learned from this:

  1. The contentType and dataType settings are absolutely necessary in the ajax() function. It won't work if they are missing. I found this out after much trial and error.

  2. To pass in an array of objects to an MVC controller method, simply use the JSON.stringify({ 'things': things }) format.

I hope this helps someone else!


Couldn't you just do this?

var things = [
    { id: 1, color: 'yellow' },
    { id: 2, color: 'blue' },
    { id: 3, color: 'red' }
];
$.post('@Url.Action("PassThings")', { things: things },
   function () {
        $('#result').html('"PassThings()" successfully called.');
   });

...and mark your action with

[HttpPost]
public void PassThings(IEnumerable<Thing> things)
{
    // do stuff with things here...
}

I am using a .Net Core 2.1 Web Application and could not get a single answer here to work. I either got a blank parameter (if the method was called at all) or a 500 server error. I started playing with every possible combination of answers and finally got a working result.

In my case the solution was as follows:

Script - stringify the original array (without using a named property)

    $.ajax({
        type: 'POST',
        contentType: 'application/json; charset=utf-8',
        url: mycontrolleraction,
        data: JSON.stringify(things)
    });

And in the controller method, use [FromBody]

    [HttpPost]
    public IActionResult NewBranch([FromBody]IEnumerable<Thing> things)
    {
        return Ok();
    }

Failures include:

  • Naming the content

    data: { content: nodes }, // Server error 500

  • Not having the contentType = Server error 500

Notes

  • dataType is not needed, despite what some answers say, as that is used for the response decoding (so not relevant to the request examples here).
  • List<Thing> also works in the controller method

Formatting your data that may be the problem. Try either of these:

data: '{ "things":' + JSON.stringify(things) + '}',

Or (from How can I post an array of string to ASP.NET MVC Controller without a form?)

var postData = { things: things };
...
data = postData

I have perfect answer for all this : I tried so many solution not able to get finally myself able to manage , please find detail answer below:

       $.ajax({
            traditional: true,
            url: "/Conroller/MethodTest",
            type: "POST",
            contentType: "application/json; charset=utf-8",
            data:JSON.stringify( 
               [
                { id: 1, color: 'yellow' },
                { id: 2, color: 'blue' },
                { id: 3, color: 'red' }
                ]),
            success: function (data) {
                $scope.DisplayError(data.requestStatus);
            }
        });

Controler

public class Thing
{
    public int id { get; set; }
    public string color { get; set; }
}

public JsonResult MethodTest(IEnumerable<Thing> datav)
    {
   //now  datav is having all your values
  }