ASP NET Model View Controller (MVC) Web Patterns

User Interface Design Patterns

To the novice developer choosing a presentation pattern for a new or enterprise web development on the Microsoft platform is a daunting task, to the experienced developer there are only three; View Model, Model-View-Presenter (MVP) or ASP.NET MVC (a Model2 derivative).

In this hub I describe each and provide the guidance on when to pick what.

Model-View-Controller

The Model-View-Controller pattern is a pattern used for separating presentation details from business domain details. The Model in the pattern is the business model/domain and the business logic of the system. The View is the presentation of the data and the user interface of the system. The View generally speaks to the Model via the Controller, which is usually responsible for gathering data from the View, and interacting with or updating the Model, as well as updating the View (either the View can be explicitly notified that it must be updated by the controller, or will be notified of changes from the Model by following an Observer pattern).

Classic MVC
Classic MVC

There are different variations to the classic MVC pattern, namely Model2, Model-View-Presenter (MVP), and PresentationModel (also known as Model-View-View-Model or just ViewModel).

PresentationModel is a pattern used in desktop Windows WPF applications and so will not be discussed here.Although it is gaining traction as a pattern for Silverlight Rich Internet Applications (RIA's).

The two patterns for web development are Model2 and MVP.

In the classic Model-View-Controller pattern, the User interacts with the View, the View notifies the Controller of the action, and the Controller updates the Model. The Model then updates the View via an Observer pattern – the View listens for notifications from the Model, and when the Model is changed, it notifies the View of the changes, allowing the View to update itself.

In the Model-View-Presenter pattern, the Presenter can be thought of as the Controller in classic MVC, however MVP is different to the classic MVC pattern in that it completely separates the View from the Model: the View can only speak to the Presenter, and the Model can only speak to the Presenter as well. There are two variations of the MVP pattern: Supervising Controller and Passive View. In Passive View, the View only ever receives notifications from the Presenter: it is the Presenter’s responsibility to retrieve details from and send details to the View. In Supervising Controller, this responsibility isn’t as strict, in that the View may notify the Presenter of any changes to itself (usually through Data Binding).

MVP
MVP

Model2 is similar to the MVP pattern in that the View and Model are completely separate and only communicate through a Controller, however it also has the concept of a Front Controller. The Front Controller is what the View speaks to in Model2 – when a User interacts with a View, the View will interact with the Front Controller, which will determine which View the request came from, and to which Controller the request must be dispatched to fulfill the request, switching to different views if necessary.

ASP.NET MVC (Model2)
ASP.NET MVC (Model2)

Enterprise Web Applications

Enterprise applications are complex (for a reason), usually due to non-functional requirements of scalability, performance and maintainability. These are typically n-tier/n-layer applications, containing a data layer, domain layer, service layer, and a client layer for the web application. ASP.NET WebForms and ASP.NET MVC are each frameworks for web applications built on top of the ASP.NET infrastructure.

ASP.NET Web Forms

ASP.NET WebForms is named so because each page in the system contains a single ASP.NET/HTML form, in which various HTML elements and ASP.NET server controls can be used.

When a page is rendered to a client, each control renders itself into the response, and ASP.NET WebForms manages the state of the controls via a concept called ViewState – the values of the controls are serialized into a hidden string on the form when being sent to the client, and deserialized back when being sent to the server so that the controls’ values can be updated and events can be raised.

Due to the ViewState, when the page is submitted back to the server, its state and control hierarchy is automatically preserved by the ASP.NET WebForms request processing engine, which goes through various steps in a page lifecyle – e.g. loading of the page, value changed events, data binding events, rendering of the page, etc. During this life cycle, various events are fired and can be handled by the page’s code behind class. This paradigm mimicks the Windows Forms desktop application paradigm on the web.

In simple web applications, the controls would typically communicate directly to the database via a data source – for example, a grid control can be connected to a table in the database using an SQL data source, and when you update the grid ASP.NET’s controls handle the updating of the database without needing this logic being hand coded in the code behind. However, with enterprise web applications, this is not possible, since the web layer/tier typically will not communicate directly with the database layer/tier, and so these controls are not really usable without a bit more work from the developer (i.e. creating a data source conforming to the control, with a proxy that communicates with the server layer/tier). This is generally acceptable, since the controls can be quite complex to manually develop, and it can also lead to a more flexible design: changes to the control or the service will affect each other less and be more flexible.

ASP.NET developers typically employ the Model-View-Presenter pattern to improve flexibility, testability, and maintenance of ASP.NET applications. Take the above example, in this case, the Supervising Controller pattern is / can be employed – the View (grid control) updates itself using data binding to the Presenter (the page’s code behind would delegate to the Presenter), the Presenter interacts with the Model (the service layer containing the business logic), and updates the View when complete (e.g. displaying fetched data from the service layer, or maybe the service returns an exception and so the Presenter could tell the View to display an error).

In WebForms, the pages are derived from a base ASP.NET Page class. Due to this tie-in to the ASP.NET framework, unit testing the Views can be difficult since the Pages require an ASP.NET runtime to function correctly – need to run inside a web server. The Presenters that the Pages delegate to are simple classes and can be completely independently unit tested. Due to this, the Passive View pattern is typically employed to aid testability of an ASP.NET application, by keeping Views as simple as possible, and giving the Presenter most if not all the responsibility of the view specific logic.

ASP.NET MVC

ASP.NET MVC is different to ASP.NET WebForms. It fits the web paradigm more closely. Each page is nothing more than an HTML page, containing the markup, scripts, and stylesheets that you include. It doesn’t automatically manage state for you using ViewState, and gives you a lot more control over what is rendered. Also, it doesn’t tie you down to using only a single form on a single page.

The typical ASP.NET WebForms developer process is creating a new page, dragging controls onto it, and hooking them up to data sources. ASP.NET MVC does not provide this – developers must have a greater understanding of HTML and HTTP, since there is not a rich control library to leverage. There are helper utilities to generate the HTML, as well as ways to render templates for different objects, but a greater understanding of HTML is probably required for MVC compared to WebForms.

Developers also have to be aware that they are responsible for maintaining the state of the application, but this is far more flexible and efficient than ASP.NET WebForms’ ViewState model which sends all the state on the page back and forth on every request; MVC allows for only data in the form to be submitted, and not the entire page’s data.

ASP.NET MVC follows the Model2 MVC pattern by default: there is a front controller which decides by convention over configuration which Controllers to dispatch to, to process a request, and these Controllers interact with the Model, and result in rendering a View (which may be different to the View that originated the request). This design pattern is part of the framework, and almost enforces a well structured and designed web application from the beginning. By using convention over configuration, developers are partially freed from having to maintain the delegation between the view and the controller, and it also simplifies navigation between views.

In ASP.NET WebForms, each URL typically maps to a single page of the same name (e.g. http://mysite/Client.aspx?Name=Jake&Surname=Sparrow would map to a page named Client under the root directory of the web application, and the Name and Surname parameters would be available to the page’s code behind class). A developer would typically extract these strings from the request, converting them to the correct type, and store them in Presentation Objects for use in the web layer (or to Data Transfer Objects that could be sent to the service layer).

In ASP.NET MVC, there is a powerful routing system which can map any URL to any Controller by parameterizing the URLs and creating routes. For example, the previous URL could be shortened to http://mysite.co.za/Client/Sparrow/Jake by using the following parameterized URL/route http://{baseUrl}/{ClientController}/{name}/{surname} , which would cause the Client Controller to be dispatched, providing the same Name and Surname parameters as before, but resulting in shorter and more memorable, meaningful, bookmarkable URLs.

This can also lead to powerful Search Engine Optimization (SEO) techniques for public facing websites. The same routing system also allows for automatic mapping from HTML request parameters to .NET classes such as Presentation Objects, or even just a list of integers if that matches correctly (e.g. an ID field) freeing the developer of manually extracting information from a web request.


The Controllers in ASP.NET MVC do not have to derive from a base class contained in the ASP.NET MVC framework, however they do have to implement an interface IController. Because they implement an interface, they can be replaced by mock objects in unit tests that depend on them, and also, unit tests for the controllers themselves can be tested in isolation – outside of a running web server. This is a great improvement to testability over ASP.NET WebForms.

ASP.NET MVC controllers do actually typically inherit from a base Controller class from the ASP.NET framework, but this class also allows for testability, since the controller doesn’t actually render the response of an HTTP request, but rather generate objects that the View can use to render itself. These are ActionResult objects (containing an optional, typesafe presentation Model) for rendering the HTTP response. The rendering engine can handle rendering responses using JSON (JsonResult), Views (ViewResult) or even just content such as plain text (ContentResult), which will eventually be rendered by the View. Assumptions about the response of a Controller action can then be tested in unit tests, as well as assumptions on the View’s presentation Model. Views can also be composed of other Views (partial Views) allowing the building of reusable components.

Based purely on the above discussions about the improvements in network performance due to lack of ViewState, increased testability, developer productivity using convention over configuration, and the closer fit to the web programming paradigm, ASP.NET MVC can be seen as an improvement over ASP.NET WebForms in general. However there is still one major selling point for ASP.NET WebForms: ASP.NET WebForms provides a set of rich controls. The next section clears up why this isn’t that big of a deal.

AJAX, Web 2.0, jQuery

AJAX and Web 2.0 are buzz words that revolve around the ability to make web applications more usable, and more semantic. In typical Web 1.0 applications, each page is a static file containing some text, some forms with input fields, and ways of sending those pages back to the web server. When you submit a form, it generates a new request, reloading a completely new page (or the same page updated). This process then continues over and over. However, it isn’t very efficient to send through and update an entire form on each request.

Take a registration form for example. Websites generally ask you to enter a unique username at registration. You enter all the required details, submit the form, and wait for it to reload. Then when it comes back (eventually) you realize that the username is already taken. You try again, and the same thing happens. Eventually you find a unique username or give up and don’t even bother registering.

To avoid this, AJAX was invented. AJAX stands for Asynchronous JavaScript and XML, and simply put, is a way of sending only parts of a webpage, and updating only parts of a webpage, when necessary. The technique leverages the use of JavaScript in the web browser.

In the above registration example, it may be more intuitive to check if the username exists on the server once the user has completed the username, and let them carry on filling in the rest of the form while this happens. When the server gets back to you, you can then display a message telling the user if their username is taken or valid. This improves usability substantially, and also performance: instead of sending the entire page over the wire each time, only the username and the validation message need be submitted when performing validation on the username; by the time the entire form needs to be submitted, it should contain valid data, reducing round trips to the server and hence performance (usually).

ASP.NET WebForms wasn’t developed with this in mind, since it was developed initially in a time before AJAX was invented or even popular. AJAX could be done manually, by talking to Web Services and then updating the page, but then the ViewState couldn’t be altered easily if at all, meaning that purely client side effects would be worthwhile implementing (e.g. for pure asynchronous receiving of data, and showing of that data).

ASP.NET AJAX was created to try to resolve this, providing the UpdatePanel control which allowed for asynchronous updating of its contents, but the same pitfalls occur with ASP.NET AJAX – each request must contain the ViewState for the ASP.NET engine to maintain state and fire events. This may actually decrease performance in some cases.

ASP.NET MVC has been developed in more recent years, and has been developed to fit the web paradigm very closely. Because of this, it is a lot easier to implement AJAX – simply using an asynchronous HTTP request.

jQuery is a popular, powerful JavaScript library that is cross-browser compliant (supports the major web browsers, including IE6+, Firefox, Safari, etc.). It eases client side scripting and AJAX, and is even included as part of the ASP.NET MVC package and project templates. jQuery UI is another library which provides dynamic, themeable web controls such as popup calendars, tabbed panels, accordion panels, sortable lists, drag-and-drop, etc., as well as some nice effects – fading in components, sliding out components, etc. There is even a theme builder on the jQuery UI website to allow easy theming of your application if you follow their CSS guidelines.

ASP.NET MVC, jQuery and jQuery UI all promote W3C standard compliancy, and in so doing, by using this combination instead of ASP.NET AJAX, there is not only improved productivity, improved application design, but also an attempt at future proofing the web based application and easing the cross browser compliance of the web application.

Choosing A Presentation Pattern

So it comes down to this, if you are using Windows Presentation Foundation (WPF) leverage the data binding capability and use the View Model pattern. If you have a requirement to reuse your Controllers/Presenters in either Windows Forms or WPF applications, use the MVP pattern with Passive Views. On the web, use ASP.NET MVC.

Presentation Patterns
Presentation Patterns

More by this Author


1 comment

fatma78 4 years ago from Navi mumbai

    Sign in or sign up and post using a HubPages Network account.

    0 of 8192 characters used
    Post Comment

    No HTML is allowed in comments, but URLs will be hyperlinked. Comments are not for promoting your articles or other sites.


    Click to Rate This Article
    working