Datetime in ASP.NET javascript and $.ajax
By Anatoly Mironov
In one of my previous blogs I wrote about serializing of javascript objects. You can do it with JSON.stringify or Sys.Serialization.JavaScriptSerializer.serialize. Both methods work fine… almost. There is a big difference when it comes to datetime objects. MS treats dates a little bit different (like RegEx and much more). Let’s try this one:
var writer = { name: "Ajgi", birthdate: new Date(1934, 8-1, 21) };
var json = JSON.stringify(writer);
var msjson = Sys.Serialization.JavaScriptSerializer.serialize(writer);
What happens if we try to parse back msjson with JSON.parse: Well, the date isn’t a valid date anymore. How can we improve it. Rick Strahl gives a solution with custom functions for serializing and deserializing of ms date. But the thing is: we don’t need any custom functions for this, not if you run ASP.NET. The only thing we need is to use serialize and deserialize functions from Sys.Serialization.JavascriptSerializer namespace which you get automatically when you add ScriptManager in ASP.NET (and you get it even automagically in SharePoint). But what about $.ajax and functions I wrote about for retrieving list items and populating them, and updating list items with listdata.svc? Well, there comes the really nice tip from Rick Strahl: not to force $.ajax to parse the response. So instead of dataType: “json”, use the plain dataType: “text”. As the result we’ll get just a text, which we, of course, will deserialize with the native code for Microsoft:…. Use text when possible. When you define json as response format:
\[OperationContract\]
\[WebGet(UriTemplate = "/GetSomething?id={id}", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)\]
object GetSomething(string id);
```ListData.svc There we have to use json as datatype, but how to prevent jQuery.parseJSON. Well a [digging into jQuery lib helped](http://code.jquery.com/jquery-1.7.1.js), just provide converters\["text json"\] property to your jQuery.ajax invokation:
$.ajax({ type: “GET”, contentType: “application/jsonp; charset=utf-8”, url: “/_vti_bin/ListData.svc/Oppgaver()”, data: {}, dataType: “json”, success: function(data) { foo = data; }, error: function() { console.log(“error”); }, converters: { “text json”: Sys.Serialization.JavaScriptSerializer.deserialize } });
#### Datetime and WCF
The response in json formats date like serialize. Let's try to send datetime to wcf service. Here is the data contract and its implementation:
[OperationContract] [WebGet(UriTemplate = “/Foo?date={date}”, ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)] string Foo(DateTime date);
public string Foo(DateTime date) { return date.ToString(“s”); }
$.ajax({ type: “GET”, contentType: “application/json; charset=utf-8”, async: true, url: “/_vti_bin/MyWcfService.svc/Foo”, data: { date: date.toISOString() }, dataType: “json”, success: function (data) { console.log(data.FooResult); }, error: function (data) { console.log(“error”); } }); //“2012-01-18T21:26:19”
Now lets try this with POST. First we change the contract:
[OperationContract] [WebInvoke(Method = “POST”, UriTemplate = “/Foo”, ResponseFormat = WebMessageFormat.Json, RequestFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Wrapped)] string Foo(DateTime date);
var date = new Date() var arg = { date: date }
var j = JSON.stringify(arg) // “{“date”:“2012-01-18T23:35:35.878Z”}” var ms = Sys.Serialization.JavaScriptSerializer.serialize(arg) // “{“date”:”\/Date(1326929735878)\/"}"
Now let's try both:
$.ajax({ type: “POST”, contentType: “application/json; charset=utf-8”, async: true, url: url, data: j, processData: false, dataType: “json”, success: function (data) { console.log(data.FooResult); }, error: function (data) { console.log(“error”); } }); // output: Foo 400 (Bad Request) // output: error
$.ajax({ type: “POST”, contentType: “application/json; charset=utf-8”, async: true, url: url, data: ms, processData: false, dataType: “json”, success: function (data) { console.log(data.FooResult); }, error: function (data) { console.log(“error”); } }); // output: 2012-01-18T23:35:35
## Comments from Wordpress.com
####
[francesco]( "francescocardin@yahoo.it") - <time datetime="2016-02-19 12:38:40">Feb 5, 2016</time>
Thanks!
<hr />