The cake is not a lie with MVC and JSON

Ever since Google Maps showed us that rich internet applications were not only possible but pretty damn cool, developers have been striving to streamline the process of communicating with web application servers without refreshing the browser.  Initially this was done by writing JavaScript to work directly with the XMLHttpRequest object; but this was tedious and not at all elegant.  Then some smart folk came up with the Prototype JavaScript framework and made everyone’s lives easier by abstracting AJAX functionality, making it easier to work with.  jQuery dazzled developers by simplifying the process even more.  XML began leaving a bad taste in everyone’s mouths, so other smart people figured out that instead of passing tagged markup data back and forth, these JavaScript frameworks could transmit and receive JSON.  Because JSON is the native way to serialize JavaScript objects, and because it is significantly less bloated than XML, it was the natural choice for future rich internet applications.

Now, I have a real passion for simplicity and elegance, so any web application framework that makes AJAX easier to write and maintain is my friend.  Since I’ve been learning ASP.NET MVC, I decided to see how it stood up to the challenge.  Like most everything else in MVC, AJAX/JSON support is cake, not a lie.  A JSON driven AJAX call in MVC consists of:

  1. the page that makes the AJAX call, which sends and/or receives data;
  2. a custom MVC action on a new or existing MVC controller that will handle the AJAX call, do the heavy data lifting, and return a result; and
  3. a custom MVC Route that maps to the controller/action in Global.asax

It’s easiest to start with the controller/action, so here we go.

There are a few things to note here, namely the return type of the Authorize() method (JsonResult instead of ActionResult), and the method called to render the data (Json() instead of View()).  Also, while any pre-defined, strongly typed object could be passed into the Json() method, an anonymous object works marvelously for simple values.  (As an aside, best practice dictates that the user repository be retrieved from an IoC container, but for the purpose of this demonstration and for space considerations, I have hard-coded it here.)  The logic in the action is very simple; we fetch a user based on credentials and return a value indicating if the user exists and if they have proper login access.  Because the action here is a simple method in a controller class, it is also possible to write automated unit tests to make sure that the method behaves as expected under a variety of conditions.

The Route for this controller/action is likewise very simple.

The route does not define any parameters for username or password.  This is because jQuery will append arguments to the route using the normal query string notation.  I suspect, but have not verified, that if a route was specified with parameters such as /{username}/{password}, and a dynamic URL was constructed in JavaScript and no arguments were passed to it, the functionality would be identical.

The actual view contains the most involved code.

The form at the bottom contains two fields, Username and Password, and a simple input button that is used for submission.  The click event of the login button calls jQuery’s built in getJSON() method, which takes the following arguments:

  1. the URL that will be used to submit the AJAX request (the URL defined in the MVC routing table);
  2. an anonymous JavaScript object with properties identical to the method arguments of the action I am calling; and
  3. a callback method that takes the return result of the AJAX request as an argument.  This result will have identical properties to the object we returned in our action method.

Based on the return value from Authorize(), I show a popup dialog indicating whether the user should be allowed to log in.  (Best practices dictate that authorization and authentication be performed by two distinct services, but I have consolidated them here for brevity.)  Because AJAX calls are asynchronous, it is important to remember that the click() event will likely exit before the getJSON() function has completed.  If you add an hourglass or twirling Web 2.0 spiral (probably not the technical name), you will want to display it before getJSON() is called and hide it in the callback function instead of at the end of the click() event to ensure that it is displayed for the duration of the request.

That’s all for now.  I will post more on MVC later, but  I think we can all agree that:

This was a triumph.
I’m making a note here: HUGE SUCCESS.
It’s hard to overstate my satisfaction.


Leave a Reply

Your email address will not be published. Required fields are marked *