Google analytics script

Latest jQuery CDN with code tiggling.

Monday, 27 December 2010

jQuery parseJSON automatic date conversion for and ISO date strings

This one's quite common. You asynchronously communicate (a.k.a. Ajax) with your server and get JSON data in return. You most probably use $.parseJSON() on the client side which actually parses JSON string and returns an object. We've all used that. But (yes, there's always a but) there's a catch. There's no defined standard for date serialization, so jQuery will not parse your dates back to dates. What the heck even native JSON parser (these days supported in all major browsers) won't do that. So you have to do it yourself. Manually. Or, modify default jQuery functionality a bit and get it done automatically.

Tuesday, 14 December 2010

Custom action method selector attributes in MVC

Some of the least customized but very useful extension points in MVC are action method selector attributes. We use them all the time without actually knowing, but we may write our own as well and make seemingly complex things trivial.

A real world example

Take for instance Twitter website. When you first visit their site, you are presented with the anonymous visitor home page that provides search capabilities, trends etc.

But when you're logged in you see a completely different page. Web address is still the same, but content is completely different. You see your home twitter page where you can send tweets and read your stream.

Using custom action method selector attributes, you can easily differentiate between such requests without using multifaceted controller actions.

Friday, 10 December 2010

Sending complex JSON objects to MVC using jQuery Ajax

jQuery has great support for sending HTML form data (that is input, select and textarea element values) back to the server using Ajax technologies by providing two main ways of preparing form data for submission - namely serialize() and serializeArray() functions. But sometimes we just don't have a form to send but rather JSON objects that we'd like to transfer over to the server. MVC on the other hand has built-in capabilities of transforming sent data to strong type objects while also validating their state. But data we're sending has to be prepared in the right way so default data binder can it and populate controller action parameters objects' properties. We can of course parse values ourselves but then we also loose the simplest yet efficient built-in validation using data annotations which is something we definitely want to use.

I know I've been sending JSON objects back to the server before, but this time I came across a problem that felt odd, since based on my previous experience should work out of the box. To my surprise it didn't. Let me explain what was going on.