CHUVASH.eu

CHunky Universe of Vigourous Astonishing SHarepoint :)

Datetime in ASP.NET javascript and $.ajax

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

Alternatives are to rever to the invokation: var s = $.ajax…., then in callback get the s.responseText and 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");
}

If we pass date formatted in ISO, we’ll get the right date:

$.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);

Pay attention to UriTemplate, now there are no GET parameters. It is important, otherwise it will conflict with the parameters passed inside the body.

Then let’s create the argument to pass:

var date = new Date()
var arg = { date: date }

Then we serialize it with JSON.stringify and Microsoft native serializing method:

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

So to pass a datetime argument in a GET request to WCF we have to create an ISO string (by running date.toISOString() or JSON.stringify(date) and removing outer quotes). In a POST request scenario we have to format the date in a WCF way, and the easiest way is to use Sys.Serialization.JavaScriptSerializer.serialise(date).

Advertisements

One response to “Datetime in ASP.NET javascript and $.ajax

  1. francesco 2016-02-19 at 12:38

    Thanks!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Discovering SharePoint

And having fun doing it

Bram de Jager talking Office 365, SharePoint and Azure

My view and thoughts on Productivity and more.

My programming life

and everything in between

SharePoint Development Lab by @avishnyakov

It is a good place to share some SharePoint stories and development practices.

SharePoint Dragons

Nikander & Margriet on SharePoint

RealActivity - Real-time and trustworthy

Blog site of founder, RealActivty - Paul J. Swider

Mai Omar Desouki - Avid SharePointer

Egyptian & Vodafoner - Senior SharePoint Consultant

Cameron Dwyer | Office 365, SharePoint, Outlook, OnePlace Solutions

Office 365, SharePoint, OnePlace Solutions & Life's Other Little Wonders

paul.tavares

Me and My doings!

Share SharePoint Points!!

By Mohit Vashishtha

Jimmy Janlén "Den Scrummande Konsulten"

Erfarenheter, synpunkter och raljerande om Scrum från Jimmy Janlén

SPJoel

SharePoint for everyone

SharePointRyan

Ryan Dennis is a SharePoint Solution Architect with a passion for SharePoint and PowerShell

SharePoint 2020

The Vision for a Future of Clarity

Aharoni in Unicode, ya mama

Treacle tarts for great justice

... And All That JS

JavaScript, Web Apps and SharePoint

blksthl

Mostly what I know about SharePoint - CommunicoCuspis

%d bloggers like this: