Home
    Shop
    Advertise
    Write For Us
    Affiliate
    Newsletter
    Contact

Easy Intro to ASP.NET MVC

What is ASP.NET MVC?

ASP.NET MVC is a framework, created by Microsoft, as an alternative to ASP.NET Web Forms. Web Forms tries to encapsulate HTML and stateless HTTP protocol and provide experience for developer like in Windows Forms programming with forms, control's events, preserved application state etc. That advantage comes with a price because it requires using of ViewState object.

 

In theory, ViewState object is keeping all state information for web form, but in practice it is implemented as large string in hidden HTML field that makes web page slow and increases bandwidth. Also, web form often has data access code, application logic code and code for rendering page output in single file which makes web application complex and hard for maintenance. Much before ASP.NET MVC is published, developers tried to divide code to different roles (tiers) to simplify large Web Forms application. Significant approach is using of three tier presentation/business/data access architecture. More about three tier architecture in ASP.NET Web Forms you can read at Three Tier Architecture in ASP.NET tutorial. Also, numeruos tutorials about speed optimization in ASP.NET advice to minimize or completely disable ViewState.

MVC is not a new term. It is abbreviation of Model-View-Controller programming methodology known from 1979. The basic roles of Model-View-Controller development are:

Model - used to maintain state of application. This part works with data, data are commonly stored in database.

View - used for output to client. Output is HTML code, rendered by user's web browser into web page. View is responsible for displaying of user interface, all needed information are received from Model. View is a classic .aspx page. Like in web forms, page supports master pages and user controls. Unlike web forms, there are no ViewState and Postback.

Controller - used for interaction with user. Controller handles user input, process data and communicate with Model to save state (for example change data in database).

Graphically, MVC can be shown like on image bellow:

MVC-Diagram
Image 1: MVC diagram

Model-View-Controller pattern is not Microsoft's new invention. There are many MVC implementations for PHP, Ruby, Pyhton, Java etc. Also, there is MonoRail open source implementation of MVC for ASP.NET. ASP.NET MVC is one more implementation of Model-View-Controller methodology, published as open source project by Microsoft.

Why separation of responsibilities to Model-View-Controller roles is good?

Separation to different roles allows us to test each of them separately. In Web Forms, all roles are usually mixed together which increase complexity and makes maintenance harder. Presentation layer is commonly used for all roles (presentation, data access and handling user input). This also encourages code duplication. Separated roles in MVC model makes project less complex. Although this is not big difference for small projects, easer maintenance becomes more and more important if you have bigger and more complex project. This is good for working in teams since every person can take single role and work on code independently of others.

Model-View-Controller enables use to create unit tests easier because now we work with one thing at the time (as latin proverb says: divide and rule). MVC implements Test Driven Development (TDD) which allows you to run automated unit tests. Any unit testing framework can be used, like MS Test, NUnit, MBUnit etc.

How to obtain ASP.NET MVC?

To download latest version of ASP.NET MVC to ASP.NET MVC download page. ASP.NET MVC is free, you can choose installation with Web Platform Installer or download .msi installation file. MVC is open source project; you can download source code to see how it works.

Why use ASP.NET MVC?

Essential advantage of MVC is separation of different roles (Model-View-Controller). Clear separation enables easier testing and maintenance. Next important feature is total control over HTML output. MVC don't use ViewState and don't create any additional HTML.Because of that, MVC pages are smaller than Web Forms and load faster. MVC doesn't need to create complex control's tree so it potentially execute faster than Web Forms.

Is MVC replacement for Web Forms?

MVC is not replacement for ASP.NET Web Forms. You simply have one more option to choose which is more suitable for you, or which is better for your current project. Both methods will exists together and you are not forced to switch to MVC if you like Web Forms. You can even use MVC and Web Forms on the same site and share data between them.

ASP.NET MVC Project Template

If you are new to Model-View-Controller concept, this may look abstract for you. Let's look how ASP.NET MVC works by creating simple MVC project. First, if you didn't already, download ASP.NET MVC from ASP.NET MVC download page and install it on your local computer. Then, open Visual Studio and go File -> New -> Project. If ASP.NET MVC is successfully installed, you'll see new project type in "New Project" dialog named "ASP.NET MVC Web Application", like on next image:

New ASP.NET MVC Project

Choose the name of your project and click OK. Next dialog will ask you would you like to create unit test project for this application:

Create ASP.NET MVC Test Project

You can select preferred test framework from drop down box. By default, Visual Studio Unit Test is installed, but you can install and use any other test framework.

When you create new project, you'll see that solution explorer shows different folders and files than common Web Forms project:

Solution explorer window of ASP.NET MVC Application

Solution contains Content, Controllers, Models and Views folders. Content folder contains default CSS file, used to define styles in application. Intuitively, Controller classes are placed in Controllers folder, Models classes are in Models folder and View .aspx pages are placed in Views folder. There is Scripts folder where JavaScript .js files are stored and App_Data folder, well known from ASP.NET Web Forms Applications, used to store data files (e.g. local .mdf Sql Server database). Except main web site project, there is second project in solution, used to perform unit tests.

This is just default directory structure; you can change it according to your needs. Default directory structure is commonly changed for large applications that contain multiple sub projects. When you create new project, there are some files placed in folders.

Controllers folder contains AccountControllers.cs and HomeController.cs files. These are example controller classes.

ASP.NET MVC Controllers Folder

Views folder has few subfolders and a several example views in them. Shared sub folder contains example use of master page and user control in MVC.

ASP.NET MVC Views Folder

Content directory contains example CSS file, named Site.css. Scripts folder contains JavaScript files needed for support for jquery and Microsoft Ajax.

ASP.NET MVC Content and Scripts Folders

When new project is created it contains simple, but working web application that can help you understand how MVC works. You can start an application by pressing F5 or through menu Debug -> Start Debugging.

ASP.NET MVC Example Application

Application contains two simple pages, Home and About. Home view receives message "Welcome to ASP.NET MVC!" from HomeController. Interesting link is "Log On" on the top of the page, where log-in system is built, including log on, log off, registration of new member, change password feature etc., all controlled from AccountController.

Very interesting is Default.aspx page, in the root of web application. If you open this file, you'll see that this is normal Web Form with code behind. Default.aspx is empty except one commented line, that says: Please do not delete this file. It is used to ensure that ASP.NET MVC is activated by IIS when a user makes a "/" request to the server. How MVC is activated, we can find out if open code behind file (Default.aspx.cs if C# is used, or Default.aspx.vb if you chosen VB.NET):

Default.aspx.cs [ C# ]

using System.Web;
using System.Web.Mvc;
using System.Web.UI;
 
namespace TestMVC
{
 public partial class _Default : Page
 {
   public void Page_Load(object sender, System.EventArgs e)
   {
     // Change the current path so that the Routing handler can correctly interpret
     // the request, then restore the original path so that the OutputCache module
     // can correctly process the response (if caching is enabled).
 
     string originalPath = Request.Path;
     HttpContext.Current.RewritePath(Request.ApplicationPath, false);
     IHttpHandler httpHandler = new MvcHttpHandler();
     httpHandler.ProcessRequest(HttpContext.Current);
     HttpContext.Current.RewritePath(originalPath, false);
   }
 }
}

Default.aspx.vb [ VB.NET ]

Partial Public Class _Default
 Inherits System.Web.UI.Page
 
 Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
   ' Change the current path so that the Routing handler can correctly interpret
   ' the request, then restore the original path so that the OutputCache module
   ' can correctly process the response (if caching is enabled).
 
   Dim originalPath As String = Request.Path
   HttpContext.Current.RewritePath(Request.ApplicationPath, False)
   Dim httpHandler As IHttpHandler = New MvcHttpHandler()
   httpHandler.ProcessRequest(HttpContext.Current)
   HttpContext.Current.RewritePath(originalPath, False)
 End Sub
 
End Class

Default.aspx is ASP.NET Web form with code behind file. ASP.NET Web Forms and ASP.NET MVC can coexist on the same site. Both are ASP.NET although MVC views have not <form runat="server"> part like web forms. Working with Views without form runat="server", control tree and events will maybe remind you on classic ASP 3.0 coding.

Notice that Models folder in example is empty. In MVC project template all is handled by controllers. Of course, if your application does anything useful you will need to store state to Sql Server database, XML file or somewhere else where Models will be used. You are not obligated to strictly use /Models folder for data access. Complete Models layer can be stored anywhere, even as separated project in assembly that allows you to use same Models in multiple projects.

Conclusion

I hope that this introduction to ASP.NET MVC was gently for you and that you found ASP.NET MVC interesting enough to study further. In next tutorial I will show how to implement basic operations on database, to read existing data and show them in View, to insert new record and update or delete existing data. To make your learning curve shorter, I strongly suggest to obtaining Pro ASP.NET MVC Framework book. It demonstrates ASP.NET MVC in action, including e-commerce, unit-testing best practices etc.


Tutorial toolbar:  Tell A Friend  |  Add to favorites  |  Feedback  |   Google