Friday, August 13, 2010

ASP.Net MVC

Here is a brief summary of the first chapter of Professional ASP.NET MVC 1.0, which is freely available to download from http://tinyurl.com/aspnetmvc. Even though it’s only the first chapter, it’s a walkthrough of a worked example and, at ~180 pages, covers a lot of ground. It’s also available for Kindle and an updated version for MVC 2.

The core of it is the model, view & controller pattern. While this isn’t a new idea, it’s still an improvement on the traditional Forms approach. The Model represents the data objects. Views are screens/pages, etc. Controllers process user requests (via URLs for example) by performing actions in the model and responding with an updated view, for example.

Applying the MVC pattern means the framework can provide built-in support for additional features, such as:

  • Routing – controls how URLs map to controllers. This makes it easy to create and maintain Search Engine Optimised (SEO or ‘Google friendly’) URLs.
  • ActionLink & RouteLink helper methods – creates URLs appropriate for the controllers. Avoids manually generating anchor tags. Can also do redirects.
  • Authentication & Authorisation – can decorate the Controllers’ action methods with role names and have the framework enforce security.

Perhaps the biggest benefit is that it’s simpler to unit test due to the greater separation of concerns – the model abstracts the database access and, if mocked, the views and controllers can be tested without a database actually being present. The final part of the chapter provides a walk through of this using dependency injection and Moq.

Early in the chapter we get an introduction to Linq To Sql, an Object Relational Mapping (ORM) tool. This can be used to quickly create an object model from SQL tables.

Some other things demonstrated include:

  • Scaffolding – quickly create basic default views (CRUD pages, etc) from templates (.aspx files).
  • Extension methods – add a method to a class without actually altering the class.
  • ViewModel classes – helper classes that expose the parts of the model needed by a specific view. Prevents exposing the entire model to every view. The ViewModel is constructed by the controller from the model.
  • Master pages & partial views – master pages allow the site’s shell to be specified once, rather than repeated on each page. Partial views are for sharing bits of views and for breaking UI things up into simpler parts.
  • Pagination – how to retrieve subsets of large result sets.
  • AJAXjQuery & JSON – demonstrates how to make a lightweight call to the website using AJAX; uses a simple jQuery text-animation effect; and sends data to a page in JSON format.

Overall, I recommend it. While many of the subjects covered will each take a further book to cover in any depth, the chapter does provide an excellent overview.

No comments: