javascript 将 MVC 模型序列化为 JSON

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10813636/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 11:07:44  来源:igfitidea点击:

Serialize MVC model to JSON

javascriptasp.netjsonasp.net-mvc-3

提问by Avi

I am trying to do a very simple task: get an MVC model, and send it back to server as JSON. I tried

我正在尝试做一个非常简单的任务:获取一个 MVC 模型,并将其作为 JSON 发送回服务器。我试过

 @Html.Raw(Json.Encode(Model));

When debugging the JS, I see that the date objects on the serialized JSON look like: /date (00064321)/and when passing the serialized JSON to the server, the dates are null on the server-side. Anyone understand what is going on?

在调试 JS 时,我看到序列化 JSON 上的日期对象如下所示:/date (00064321)/当将序列化 JSON 传递给服务器时,服务器端的日期为空。有人明白这是怎么回事吗?

回答by VJAI

Instead of JSON encoding the model directly you have to create an anonymous object converting the date-time properties to strings.

您必须创建一个匿名对象,将日期时间属性转换为字符串,而不是直接对模型进行 JSON 编码。

Ex.

前任。

var meeting = new Meeting 
              { 
                  Name = "Project Updates", 
                  StartDateTime = DateTime.Now 
              }; 

Passing directly the model..

直接传递模型..

@Html.Raw(Json.Encode(meeting))

produces

产生

{"Name":"Project Updates","StartDateTime":"\/Date(1338381576306)\/"} 

and

@Html.Raw(Json.Encode(new { 
                  Name = meeting.Name, 
                   StartDateTime = meeting.StartDateTime.ToString()
}))

produces

产生

{"Name":"Project Updates","StartDateTime":"5/30/2012 6:09:36 PM"} 

as expected.

正如预期的那样。