2

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.

Haidar
  • 123
  • 1
  • 12
  • You need `contentType: 'json'` (and remove `traditional: true`) –  Apr 05 '16 at 23:45
  • Thanks, it works, could you post it as answer and explain me the difference between data-type and content-type – Haidar Apr 05 '16 at 23:50
  • Shyju has already added one. Refer also [What is content-type and datatype in an AJAX request?](http://stackoverflow.com/questions/18701282/what-is-content-type-and-datatype-in-an-ajax-request) –  Apr 05 '16 at 23:54
  • @StephenMuecke thanks a lot – Haidar Apr 05 '16 at 23:56

1 Answers1

3

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

Shyju
  • 214,206
  • 104
  • 411
  • 497