Saturday, April 11, 2009

ASP.NET MVC Framework

Microsoft has finally made available the 1.0 release of the ASP.NET MVC Framework. The framework provides a new way of developing ASP.NET web applications that is based around the classic Model View Controller design pattern. In an MVC app instead of each page being a separate file there are three components that work together to deliver a web page to the user:

Model – The model is the class or classes that represent the data that will be displayed on the page. This may be a group of in memory objects, a class that accesses an XML file, a database access layer, etc. The framework doesn’t put any restrictions on what the model can be.

View – This is the file that generates the output that is sent to the browser. Views are HTML files that can also contain scripts to embed dynamic data in the output. These are very similar to .ASPX files used in ASP.NET web forms. The view only works with data that is passed to it by the controller.

Controller – The controller class is responsible for handling input from the user, updating the model, extracting data from the model needed to build a view and finally deciding what view should be displayed. The controller doesn’t have any direct control over how that data will be presented, that will be handled by the view.

It’s important to note that the MVC Framework is not layered on top of the existing Web Forms model, but instead is a totally different way of developing ASP.NET apps. You do lose a lot of things that you may have gotten used to in web forms. In MVC there is no viewstate, no event handlers, and you can only make limited use of server controls. Giving up these things has its upside; it makes the page processing cycle much simpler and thus much faster. It also makes it much easier to get full control of the HTML output.

The biggest advantage to using MVC is the separation of concerns that is promotes. By having a clear separation between display, data and control it makes it easier to maintain large applications and also makes I much easier to perform automated unit testing.

I have been doing some work with the MVC Framework and although there is a learning curve it wasn’t too hard to get up to speed with it. I don’t think MVC will totally replace Web Forms, but I think it is very well suited to certain types of applications. As you start developing new ASP.NET apps you will want to look at the pros and cons of MVC and Web Forms and decide which would be more appropriate for a given application.

If you want to give it a try you can download the MVC Framework from http://www.asp.net/mvc/. You will need to be running Visual Studio 2008 or Visual Web Developer 2008 SP1 to use it.

No comments: