1

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

tereško
58.5k26 gold badges100 silver badges151 bronze badges
asked Jun 4, 2013 at 9:11
1
  • Which date format are you using on the client? Commented Jun 4, 2013 at 9:14

2 Answers 2

1

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?

answered Jun 4, 2013 at 12:22
1
  • That's right you should not be using the native JavaScriptSerializer but NewtonSoft's Json.NET serializer. Commented Jul 1, 2013 at 21:07
0

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);
}
answered Jun 4, 2013 at 10:27

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.