Serialize MVC model to JSON

2019-09-03 10:13发布

问题:

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?

回答1:

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.