17

I have been struggling to find a solution to this problem.

In my code, I am building up an array of an object;

var $marks = [];

var mark = function ( x, y, counter ){
    this.x = x;
    this.y = y;
    this.counter = counter;
}

$marks.push(new mark(1, 2, 0));   
$marks.push(new mark(1, 2, 1));
$marks.push(new mark(1, 2, 2));

Now I want to post this data to a MVC controller, so I would think that the data type in the controller would be a List<Mark> Marks or an array of Marks.

To post the data, I have tried;

var json = JSON.stringify($marks);
$.post('url', json).done(function(data){ /* handle */ });

OR

var json = { Marks: $marks };
$.post('url', json).done(function(data){ /* handle */ });

The second way, when looking at the data posted, looks like this

Marks[0][x]: 1
Marks[0][y]: 2
Marks[0][counter]: 0
Marks[0][x]: 1
Marks[0][y]: 2
Marks[0][counter]: 1
Marks[0][x]: 1
Marks[0][y]: 2
Marks[0][counter]: 2

But I am not sure how to translate this into a strongly typed object in the controller?

My Controller looks like this;

[HttpPost]
public ActionResult JsonSaveMarks(List<Mark> Marks){
    // handle here
}

My Mark class looks like this;

public class Mark{
     public string x { get; set; }
     public string y { get; set; }
     public string counter { get; set; }
}

I have read through other similar problems about creating a custom JsonFilterAttribute, or using the System.Web.Script.Serialization.JavaScriptSerializer class, but I cant get anything to work

Is there something obvious I am missing here? Have I got the DataType in the controller completely wrong? How can I convert this data posted into a strongly typed object?

Many Thanks

3
  • what does your Mark-class in MVC look like? Commented Apr 4, 2012 at 8:52
  • @Pbirkoff I have updated the question with the class Commented Apr 4, 2012 at 8:55
  • 1
    check this question, especially the first answer: stackoverflow.com/questions/4789481/… Commented Apr 4, 2012 at 9:03

3 Answers 3

15

$.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/

Sign up to request clarification or add additional context in comments.

3 Comments

Ah, you beat me to it, had the same idea
Thanks! After all that headache I knew it would be something simple! changed my code to using $.ajax() also, passed the data through as JSON.stringify($marks)
Thanks so much. It was the content type in my case.
14

@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);
    }
});

Comments

2

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

1 Comment

this code only post json object not an object array

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.