帖子数组作为JSON到MVC控制器 [英] Post Array as JSON to MVC Controller
问题描述
我一直在努力找到解决这个问题。
I have been struggling to find a solution to this problem.
在我的code,我建立了一个对象的数组;
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));
现在我想张贴此数据到MVC控制器,所以我认为,在控制器中的数据类型将是列表与LT;马克和GT;标记
或标记的数组。
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 */ });
或
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; }
}
我已经通过其他类似的问题有关创建自定义<读href=\"http://stackoverflow.com/questions/320291/how-to-post-an-array-of-complex-objects-with-json-jquery-to-asp-net-mvc-control\">JsonFilterAttribute,或者使用System.Web.Script.Serialization.JavaScriptSerializer一流的,但我不能得到任何工作。
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?
非常感谢
推荐答案
$后()
不允许您设置您的AJAX调用的内容类型 - 你可能会发现(如果你使用Fiddler),你的JSON字符串正在与内容类型发送应用程序/ x-WWW的形式urlen codeD(默认设置),然后导致Asp.Net MVC以正确跨preT的数据包。
$.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.
您可以尝试使用 $。阿贾克斯()
代替,并设置内容类型为application / JSON?
Can you try using $.ajax()
instead, and set the content type to "application/json"?
http://api.jquery.com/jQuery.ajax/
这篇关于帖子数组作为JSON到MVC控制器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!