In a MVC4 application, I'm passing my view model to the controller action method AsyncUpdateOrderLine:
function updateQuantity(sender) {
...
var model = @Html.OrderToJson(Model)
$.ajax({ type: "POST",
url: "/Order/AsyncUpdateOrderLine",
datatype: "json",
contentType: 'application/json',
data: JSON.stringify({ orderLineId: orderLineId, quantity: quantity, myOrder: model }),
success: function (msg) {
...
}
});
}
When I check the myOrder parameter in runtime, I notice that the DateTime properties (such as OrderDate) of my model are not deserialized properly: 1/1/0001. Other properties in the deserialized model look fine. My OrderToJson method looks like this:
public static MvcHtmlString OrderToJson(this HtmlHelper html, MyViewModel viewModel)
{
var json = new JavaScriptSerializer().Serialize(viewModel);
return MvcHtmlString.Create(json);
}
I already tried to set the Kind of the DateTime properties to Utc, but this doesn't do anything for me. I also made a small console application to test serializing and deserializing DateTime properties. Needless to say, in that sample app there's no issue. It might be related to the way that MVC deserializes the JSON string. Any tips to solve this issue?
Regards, Nils
-
Which date format are you using on the client?Huske– Huske06/04/2013 09:14:55Commented Jun 4, 2013 at 9:14
2 Answers 2
Try using the Json.NET serializer to get a better output on the javascript side:
@Html.Raw(JsonConvert.SerializeObject(Model))
Check the locale on the client. How is the date being parsed? as a string? as a js date object?
-
That's right you should not be using the native JavaScriptSerializer but NewtonSoft's Json.NET serializer.Marko– Marko07/01/2013 21:07:52Commented Jul 1, 2013 at 21:07
MVC internally uses the DataContractJsonSerializer
. The problem is probably that both are serializing/deserializing dates differently.
You can try to replace the JavascriptSerializer
with the DataContractSerializer:
public static MvcHtmlString OrderToJson(this HtmlHelper html, MyViewModel viewModel)
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(MyViewModel));
string json = string.Empty;
using (MemoryStream stream = new MemoryStream())
{
serializer.WriteObject(stream, viewModel);
json = Encoding.Default.GetString(stream.ToArray());
}
return MvcHtmlString.Create(json);
}