ngruson
ngruson

Reputation: 1338

JSON date serialization issue in ASP.NET MVC 4

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

Upvotes: 1

Views: 981

Answers (2)

amhed
amhed

Reputation: 3659

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?

Upvotes: 1

Kenneth
Kenneth

Reputation: 28737

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

Upvotes: 0

Related Questions