序列化MVC模式JSON [英] Serialize MVC model to JSON

查看:100
本文介绍了序列化MVC模式JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图做一个非常简单的任务:获得一个MVC模式,并发送回服务器JSON。我试过

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

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

在调试JS,我看到的序列化JSON的日期对象如下: /日期(00064321)/ 并通过序列化的JSON到服务器时,该日期是在服务器侧空。任何人都明白是怎么回事呢?

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?

推荐答案

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

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

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

直接传递模型。

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

产生

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

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

产生

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

如预期。

这篇关于序列化MVC模式JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆