C# 将数组作为 JSON 发布到 MVC 控制器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10007722/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Post Array as JSON to MVC Controller
提问by Tim B James
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> Marksor an array of Marks.
现在我想将此数据发布到 MVC 控制器,因此我认为控制器中的数据类型将是一个List<Mark> 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;
我的 Mark 课看起来像这样;
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.JavaScriptSerializerclass, but I cant get anything to work
我已经阅读了有关创建自定义JsonFilterAttribute或使用System.Web.Script.Serialization.JavaScriptSerializer类的其他类似问题,但我无法获得任何工作
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
非常感谢
采纳答案by Steve Hobbs
$.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.
$.post()不允许您设置 AJAX 调用的内容类型 - 您可能会发现(如果您使用 Fiddler)您的 Json 字符串发送的内容类型为“application/x-www-form-urlencoded”(默认设置)然后导致 Asp.Net MVC 错误地解释您的数据包。
Can you try using $.ajax()instead, and set the content type to "application/json"?
您可以尝试使用$.ajax(),并将内容类型设置为“application/json”吗?
回答by tugberk
@SteveHobbs has the right answer here. On the other hand, you should JSON.stringifythe JavaScript payload as you did. If you do it the other way, you will get an exception telling something like "Invalid JSON primitive"while deserializing the data coming in.
@SteveHobbs 在这里有正确的答案。另一方面,您应该JSON.stringify像您一样处理 JavaScript 负载。如果您以另一种方式执行此操作,则在反序列化传入的数据时,您将收到一个异常,告知诸如“无效的 JSON 原语”之类的信息。
Here is the complete solution to your sample:
这是您的样品的完整解决方案:
$.ajax({
url: '/home/index',
type: 'POST',
data: JSON.stringify($marks),
dataType: 'json',
contentType: 'application/json',
success: function (data, textStatus, jqXHR) {
console.log(data);
}
});
回答by Ricardo de Assuncao Goncalves
This code fixed my problem:
这段代码解决了我的问题:
C# classes:
C# 类:
public class MediaAccountContent
{
public Guid IdMedia { get; set; }
public string Value { get; set; }
}
public class User
{
public string Firstname { get; set; }
public string Lastname { get; set; }
public List<MediaAccountContent> MediaAccountContents { get; set; }
}
MVC action:
MVC动作:
public ActionResult SavePlace(User user)
{
return Content("OK");
}
Javascript:
Javascript:
var mediaAccountsJson = [];
for (var i = 0; i < 10; i++)
{
mediaAccountsJson.push({
IdMedia: i,
Value: "AAA" + i
});
}
var datatItem =
{
Firstname: "Test Firstname",
Lastname: "Test Lastname",
MediaAccountContents: mediaAccountsJson
};
$.ajax({
type: "POST",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(datatItem),
url: urlAction,
success: function (status) {
}
});
Make the changes you need for your scenario and enjoy! :)
对场景进行所需的更改并享受!:)

