我一直在努力寻找解决此问题的方法。将数组作为JSON传递给MVC控制器
在我的代码中,我构建了一个对象的数组;
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<Mark> Marks
或标记的数组。
要发布数据,我试过了;
var json = JSON.stringify($marks);
$.post('url', json).done(function(data){ /* handle */ });
OR
var json = { Marks: $marks };
$.post('url', json).done(function(data){ /* handle */ });
第二种方式,望着发布数据时,看起来像这样
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
但我不知道如何翻译成一个强类型对象本在控制器中?
我的控制器看起来像这样;
[HttpPost]
public ActionResult JsonSaveMarks(List<Mark> Marks){
// handle here
}
我的马克班看起来像这样;
public class Mark{
public string x { get; set; }
public string y { get; set; }
public string counter { get; set; }
}
我已经通过有关创建自定义JsonFilterAttribute,或使用System.Web.Script.Serialization.JavaScriptSerializer类其他类似问题阅读,但我不能得到任何工作
有什么明显的,我在这里失踪?我有控制器中的DataType完全错误吗?如何将这些数据转换为强类型对象?
非常感谢
你在MVC中的Mark-class是什么样的? – Pbirkoff 2012-04-04 08:52:45
@Pbirkoff我已更新与类 – 2012-04-04 08:55:13
检查此问题,尤其是第一个答案的问题:http://stackoverflow.com/questions/4789481/post-an-array-of-objects-via-json-to-asp -net-mvc3 – Pbirkoff 2012-04-04 09:03:47