Click here to Skip to main content
Click here to Skip to main content

Booting ASP.NET MVC

By , 15 Jul 2010
 

MVC Pattern Overview

Model-View-Controller (MVC) is a classic design pattern which is used to maintain multiple views of the same data. MVC pattern works on the clean separation of objects into one of three categories — models for maintaining data, views for displaying all or a portion of the data, and controllers for handling events that affect the model or view(s).

MVC pattern was popularly used in SmallTalk in the early 80s. VC++ is other language in the C family in MVC usage and now we are talking about ASP .NET MVC.

How MVC Pattern Works?

Because of the above loosely coupled separation, multiple views and controllers can interface with the same model as described in the below example. Even new types of views and controllers that never existed before can interface with a model without forcing a change in the model design.

As an example, let us take the text box with up and down ticker User Interface component. Let's assume that it reads the temperature data from the user. As per MVC design, Model is temperature data and View is text box to display the data. There are three controllers (text box, up ticker and down ticker).

MVC pattern allows any number of controllers to modify the same model. Whenever the text field has focus, hitting the enter key fires off an action event that may potentially be handled by a different action listener than the one handling action events. Let's see how the work flows in this example.

When the page (with temperature) is loaded, User Interface-View retrieves the data via thick link to Data-Model. Also, view subscribes for Data-Model update event. In the similar line, Temperature Text Box subscribes to the associated controller. When the user updates the existing data via controller, Model get updated through a thick line mark. Apparently, the updated data is refreshed in the view due to the subscription methodology. In simple terms, Model-View-Controller are well connected with each other and automatic updates are cascaded by design.

ASP.NET MVC Framework

If you are looking to build your web applications using a MVC approach, ASP.NET MVC Framework option is:

  • Very clean and easy to use
  • Enables you to easily maintain separation of concerns in your applications, as well as facilitate clean testing and TDD (Test Driven Development)
  • Highly extensible and pluggable
  • Supports using the existing ASP.NET .ASPX, .ASCX
  • Does not use the existing post-back model; instead, you'll route all end-user interactions to a Controller class

Building ASP.NET MVC Application

As a pre-requisite, we need ASP.NET MVC 2 Framework in VS 2008 (min). Let's get our hands boot up with the first application in ASP.NET MVC Framework. The problem statement is to greet the user by his/her name.

To start with, let's create a new empty ASP.NET MVC Web Application from Visual Studio Installed Templates. VS will question whether you want to create some test through tools. Let's disable this option at this moment by clicking 'No, do not create a unit test project'.

New MVC Project Creation

After creating the new empty MVC project, the solution explorer contains the below source code structure.

Global.asax Router

On noticing it, the new solution contains new folders Models, Controllers and Shared(Views). Global.asax contains our own MVC Application class derived from Web.HttpApplication. It has static RegisterRoutes as the router for the incoming requests.

MapRoute is actually not part of the routing system; it’s an extension method added to RouteCollection by ASP.NET MVC. As written in our RegisterRoutes method, calling MapRoute will add a single route to the RouteCollection. Like Application_Start, most web applications will have only one RouteCollection, stored in System.Web.Routing.RouteTable.Routes.

The most important thing that MapRoute does is to create and pass an MvcRouteHandler instance when adding the route to the RouteCollection. This ensures that when ASP.NET handles an incoming URI which matches this route, control will be passed to the MVC framework for handling the request.

Model Creation

To start building, let's design the model for our MVC application. As per the problem statement, user name information is considered as the model and so newly created model class is written as:

 namespace MvcHelloApplication.Models  {
        public class HelloUser {
             public String FullName { get; set; }
        }
 }

Controller Creation

Let's add a new controller for our MVC application by right clicking on Controllers folder. It generates the new class derived from System.Web.Mvc.Controller with default Index method. As per the problem statement, let's add our own method namely GreetUser. GreetUser controller creates a new view with HelloUser Model set and returns as ActionResult.

 public ActionResult GreetUser(String id)  {
        HelloUser user = new HelloUser();
        user.FullName = id;
        ViewData["FullName"] = user.FullName;
        return View();
 }

View Creation

It's time to add the View part in MVC. Right-click on the "Views" folder and add a new folder called "Hello". Now right-click on the new "Hello" folder and select: Add -> New Item. Then pick the "MVC View Content Page" and call the new file "Greeting.aspx". Prior to build view, we need to design our Site Master page under Shared folder of Views.

Last Step-Router

The last step is to review the global.asax file for the "RegisterRoutes" method setup through "routes.MapRoute" code. It stores a list of routes, translates an incoming URI into lists of values and tokens, and passes those lists to the handler specified on the route. And, it is used to call the appropriate Controller/Action.

 routes.MapRoute(
        "Default",
        "{controller}({action})({id})",
        new { controller = "Home", action = "Index", id = "" }
 );

Replaceable parameters within the URL are defined using a { } syntax. Default map URLs to Controllers using the above format when determining which Controller class to instantiate, and which Action method to invoke (along with which parameters should be passed in).

Running with Parameters

By default, id is the parameter for the supplied URL. On execution, URL 'http://localhost:1158/Hello/GreetUser/TestUser' supplies the FullName to GreetUser using the default 'id' parameter.

If the user wants other parameters, then query string like 'http://localhost:1158/Hello/GreetUser?UserLogin=testlogin' is the solution.

Points of Interest

I hope this long explanation has taken some of the mystery out of what ASP.NET MVC Framework does. It is an evolving and emerging ASP.NET Framework with a lot of updates/changes. But, the fundamental knowledge will be a huge benefit to catch up on the newer technologies.

History

  • Version 1.0 - Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

GanesanSenthilvel
Architect
India India
Member
Currently working as IT Solution Architect for Financial Services applications. Out of 18+ years, spent six career years at major IT firms in USA. Basically from C, C++, VC++, C# family, extending to the emerging Big Data and Cloud technology. Loves driving, spending time with friends&family, building my farm house.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralWorking projectmemberL Hills21 Jul '10 - 4:43 
This is a nice article, however I think it would be improved with the addition of a working project.
 
I know it's only one page but but I found that using /hello/Greetuser as a url didn't work and I needed to play with global.ascx. This may have been because I was using the asp.net mvc 2 project templates but a working project would have clarified things.
 
Thanks anyway, it inspired me to look at the subject again.

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 16 Jul 2010
Article Copyright 2010 by GanesanSenthilvel
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid