Doug Seven

Director of Product Management, Visual Studio

Implementing the MVC Pattern in ASP.NET

On Monday I presented to the Redmond/Seattle .NET Developer’s Association. The topic was, Implementing the MVC Pattern in ASP.NET. Interestingly, the ASP.NET Framework follwos the MVC pattern (or at least it could be argued that it does, although I think it misses the mark a bit). In the talk I discusses the Model-View-Controller (MVC) pattern and the benefits it provides for seperation of concerns, the ability to work in parralell, and added testability.

During the talk I showed a “typical” ASP.NET implementation in which the mark-up is in an ASPX file, the codebehind file supports it, and makes calls to a SQL instance. I then show how to implement MVC to render the same result. I create a Model to transport the data from the DB. It expoese the data as a ReadOnlyCollection, and exposes Add, Remove and Clear methods to alter the collection. This enables the Model to be aware of any changes made to the collection. I create a Controller, which mimicks the Model methods, so that it can act as the intermediary betweent he View and the Model. The Controller constructor requires an instance of IView to be provided. This gives the Controller the hooks into the View it needs. The View is the ASP.NET page. I added the IView implementation to the page’s codebehind class, and in the Page.Load event, I create the Controller by passing it “this” (i.e. MyController controller = new MyController(this);).

My demo is based on the example in aietc’s blog post.

The attachment includes my demo code (SQL Express file included) and my slide deck (all 4 slides).

Technorati tags: ,