Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post Array as JSON to MVC Controller

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

like image 973
Tim B James Avatar asked Apr 04 '12 08:04

Tim B James


1 Answers

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

like image 151
Steve Hobbs Avatar answered Oct 06 '22 10:10

Steve Hobbs