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

前端 未结 13 1730
逝去的感伤
逝去的感伤 2020-11-22 14:22

I\'m trying to pass an array of objects into an MVC controller method using jQuery\'s ajax() function. When I get into the PassThing() C# controller method, the argument \"t

13条回答
  •  [愿得一人]
    2020-11-22 14:28

    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 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!

提交回复
热议问题