Skip to content Skip to sidebar Skip to footer

Serialize Mvc Model To 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)); When debugging the JS, I see that the date obje

Solution 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.

Post a Comment for "Serialize Mvc Model To Json"