Tuesday, September 23, 2008

MVC-Model View Controller Pattern for ASP.NET

Model view controller is nothing but a design pattern used to achieve customizability in our application. Change is the only thing in the world, which will never change. All the products that we develop to our clients will undergo many changes. To accommodate these changes we should concentrate more on our design.

Good Layering Approach


MVC follows the most common approach of Layering. Layering is nothing but a logical split up of our code in to functions in different classes. This approach is well known and most accepted approach. The main advantage in this approach is re-usability of code. Good example of layering approach is UI, Business Logic, and Data Access layer. Now we need to think how we can extend this approach to give us another great advantage customizability. The answer to this is using Inheritance. Inheritance is one of the powerful concepts in oops. .Net supports this in a nice way.


View Layer


Our View /UI layer should only have UI related validations in it. We should not have any Business Logic in to it. This gives us the flexibility to change the UI at any time and we can also have different UI for different customers. We can even have web based UI for some of the clients.


Controller /Director


Controller is the layer, which responds to the events in the UI. For example Save button click on my employee master screen. This layer should act as an intermediate between our View and Model. Initially we may think that this layer is not necessary. I am also not convinced with this layer. But still we need to think. May be after some days we will get answer for this. This layer will act as just event redirector.


Model


This layer has all our business logic. This is the most important layer. This layer will have our core functionality. This layer should be designed in such a way that out core and complex logic should be designed as functions and these function should be marked as overridable so that the inheriting classes can re-use the logic or override the logic. We should not make all the functions in the layer as overridable this may raise some security threats. All the database operations should be done in the Model base class. All the inheriting classes should call this method to do database updates.


The Model-View-Controller and Model-View-Presenter Patterns


An example - Class view

Visual Studio 2008 -MVC- Template view





The ASP.NET MVC pattern interms of code is dramatically changed. Now, if we have Visual Studio.net 2008, the MVC project template is bundled with the software. For express editions we can download the templates [you must have Express editions with SP1] from Microsoft site. For more details http://www.asp.net/learn/mvc-videos/

No comments:

Post a Comment