Haidar
Haidar

Reputation: 123

How to send array of objects to a controller method?

I need your help, I have this piece of code in the controller side

public bool DraftMessage(message[] draftMessages, HttpPostedFileBase[] files = null)
{    
  return true;
}

and I use this client side code to send the data

 function DraftMessage()
    {
        var myArray = [{ 'To': [1, 2], "Title": "Hello" }, { 'To': [1, 2], "Title": "Hello" }]

        $.ajax({
            type: "POST",
            url: "@Url.Action("DraftMessage","Activities")",
            datatype: "json",
            traditional: true,
            data: JSON.stringify({ draftMessages: myArray }),
                beforeSend: function () { }
        }).done(function (data) {});
    }
    $("input, select, textarea").change(function () { DraftMessage(); });
    var contents = $('.note-editable').html();
    $(".compose-message").on("blur", ".note-editable", function () {
        if (contents != $(this).html()) {
            DraftMessage();
            contents = $(this).html();
        }
    });

but when I debug it I found that the array of messages in the controller is null so could anyone guide me about what I did wrong and help me to fix this issue.

Upvotes: 2

Views: 2111

Answers (1)

Shyju
Shyju

Reputation: 218722

You need to set contentType as "application/json"

function DraftMessage() {
    var myArray = [{ 'To': [1, 2], "Title": "Hello" }, { 'To': [1, 2], "Title": "Hello" }];

    $.ajax({
        type: "POST",
        url: "@Url.Action("DraftMessage","Home")",
        contentType: "application/json",
        data: JSON.stringify({ draftMessages: myArray })
    }).done(function (data) {
        console.log(data);
    });
}

The default value of contentType header is "application/x-www-form-urlencoded" . Since we are sending the json stringified version of a a complex data structure, we should explicitly specify the contentType

Upvotes: 3

Related Questions