Roger Johansson
Roger Johansson

Reputation: 23214

How to correctly return .NET dates from ASP.NET MVC to Javascript/JQuery

I've found a million posts about serializing .NET dates to json. Yet, I'm unable to get any of those to work correctly.

Here is my serialzier code so far:

string javascriptJson = JsonConvert.SerializeObject(result, 
   new JavaScriptDateTimeConverter());
return Content(javascriptJson, "application/json");

This returns an unescaped string containing the correct JSON, and looks completely right when viewing it in the browser. (e.g. dates looks like : date: new Date(023198928) and as far as my limited javascript skill goes, that is how it should look like)

However, I can not get JQuery to understand this, either I get back a plain javascript string, or it simply fails, I want the deserialized object.

I've tried both $.get and $.getJSON

Ideas ?

Upvotes: 1

Views: 202

Answers (2)

Roger Johansson
Roger Johansson

Reputation: 23214

It turns out that even though the response from my service is valid javascript, it is not valid Json.

You can not return "{ date : new Date(24342) }" as it opens up for script injection I guess. I reverted back to the standard .NET Json serializer and simply parsed the "\Date(343)\" that it returns..

Upvotes: 0

Treb
Treb

Reputation: 20271

These are not the mothods you are looking for...

jQuery.get():
Retrieve one of the DOM elements matched by the jQuery object.

jQuery.getJSON():
Load JSON-encoded data from the server using a GET HTTP request.

Try jQuery.parseJSON() instead:
Takes a well-formed JSON string and returns the resulting JavaScript object.

Upvotes: 1

Related Questions