Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
211 views
in Technique[技术] by (71.8m points)

c# - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...