Post Array as JSON to MVC Controller Post Array as JSON to MVC Controller json json

Post Array as JSON to MVC Controller


$.post() doesn't allow you to set the content type of your AJAX call - you might find (if you use Fiddler) that your Json string is being sent with a content-type of "application/x-www-form-urlencoded" (the default setting) which then causes Asp.Net MVC to incorrectly interpret your data packet.

Can you try using $.ajax() instead, and set the content type to "application/json"?

http://api.jquery.com/jQuery.ajax/


@SteveHobbs has the right answer here. On the other hand, you should JSON.stringify the JavaScript payload as you did. If you do it the other way, you will get an exception telling something like "Invalid JSON primitive" while deserializing the data coming in.

Here is the complete solution to your sample:

$.ajax({    url: '/home/index',    type: 'POST',    data: JSON.stringify($marks),    dataType: 'json',    contentType: 'application/json',    success: function (data, textStatus, jqXHR) {        console.log(data);    }});


This code fixed my problem:

C# classes:

public class MediaAccountContent{    public Guid IdMedia { get; set; }    public string Value { get; set; }}public class User{    public string Firstname { get; set; }    public string Lastname { get; set; }    public List<MediaAccountContent> MediaAccountContents { get; set; }}

MVC action:

public ActionResult SavePlace(User user){    return Content("OK");}

Javascript:

    var mediaAccountsJson = [];    for (var i = 0; i < 10; i++)    {        mediaAccountsJson.push({            IdMedia: i,            Value: "AAA" + i        });    }    var datatItem =    {        Firstname: "Test Firstname",        Lastname: "Test Lastname",        MediaAccountContents: mediaAccountsJson    };    $.ajax({        type: "POST",        contentType: 'application/json; charset=utf-8',        data: JSON.stringify(datatItem),        url: urlAction,        success: function (status) {        }    });

Make the changes you need for your scenario and enjoy! :)