将数组作为 JSON 发布到 MVC 控制器
我一直在努力寻找解决此问题的方法.
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));
现在我想将此数据发布到 MVC 控制器,因此我认为控制器中的数据类型将是 List;标记
或标记数组.
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.
要贴数据,我试过了;
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
}
我的 Mark 类看起来像这样;
My Mark class looks like this;
public class Mark{
public string x { get; set; }
public string y { get; set; }
public string counter { get; set; }
}
我已经阅读了有关创建自定义 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?
非常感谢
$.post()
不允许您设置 AJAX 调用的内容类型 - 您可能会发现(如果您使用 Fiddler),您的 Json 字符串发送的内容类型为application/x-www-form-urlencoded"(默认设置),这会导致 Asp.Net MVC 错误地解释您的数据包.
$.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.
您可以尝试使用 $.ajax()
代替,并将内容类型设置为application/json"吗?
Can you try using $.ajax()
instead, and set the content type to "application/json"?