最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Serialize MVC model to JSON - Stack Overflow

programmeradmin4浏览0评论

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));

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?

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));

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?

Share Improve this question edited Oct 22, 2014 at 14:16 alex 7,47111 gold badges59 silver badges113 bronze badges asked May 30, 2012 at 9:35 AviAvi 1,9644 gold badges19 silver badges31 bronze badges 1
  • Post your ajax code and action method so we can see what is going on – CD Smith Commented May 30, 2012 at 12:15
Add a ment  | 

1 Answer 1

Reset to default 5

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

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.

发布评论

评论列表(0)

  1. 暂无评论