The View and the Controller

How Communication Occurs between the Two Main Actors in an ASP.NET MVC Scenario





The View and the Controller

How Communication Occurs between the Two Main Actors in an ASP.NET MVC Scenario


By Dino Esposito


The Model-View-Controller (MVC) pattern was introduced about 30 years ago to address a more effective way of building applications. MVC contrasts monolithic applications where the responsibilities are not neatly separated between components. For some reason, in 30 years, it never has captured the hearts of developers to the point of becoming a worldwide standard across all possible platforms. Instead, the advent of object orientation first, and RAD tools later, grabbed developers attention and basically made us move to a different type of monolithic application. More precisely, the availability of powerful RAD tools made it very simple for so many people to place code straight in the handler of a UI event. As a result, very few savvy developers kept focusing on good design principles. The principle of Separation of Concerns (SoC) was blissfully relegated to the rank of one of those it-would-be-nice-to-have-if-only-there-were-enough-time things.


So what s this sudden hype over MVC? As far as ASP.NET is concerned, it has to do with the Microsoft commitment to offer an alternative and optional ASP.NET Framework that allows us to write applications with a clear separation of concerns and, subsequently, a much higher level of testability. This framework is the ASP.NET MVC Framework.


You don t need this new framework to add SoC and testability to your Web Forms applications. You can apply SoC in your traditional development cycle. MVC (and its richer variation, named Model-View-Presenter) are simply design patterns whose implementation is in the hands of architects and developers working on the project. If you choose to add MVC or MVP manually, the burden of designing your code properly is entirely on you. The ASP.NET MVC Framework, instead, forces you to reason in a different way; by doing so, you get a free MVC implementation.


In this article, I ll focus on the internal mechanics of applications based on the ASP.NET MVC Framework. In particular, I ll look at the interaction between two of the actors active in an MVC scenario: view and controller.


Members of the Triad

According to the MVC pattern, applications are based on three main actors: the model, the view, and the controller. These actors often are referred to as the MVC triad. The model is a reference to any object, or object model, that contains the application and/or business logic. The model contains, or can access, all the data being worked on in the screen. The view is made of interactive controls, such as text fields, buttons, checkboxes, and lists, and waits for any user gestures. For example, when the user selects a new item in a dropdown list, the view forwards the call to the controller. The controller is the actor responsible for deciding what to do, then completing that action. Usually, the controller invokes a method on the model to service the user request.


How the view forwards requests to the controller is an aspect of the MVC pattern that largely depends on platform, languages, and development tools. In a .NET application, the view handles its events in the code-behind class, and all it does is invoke a particular action method on the controller class. This holds true for classic ASP.NET, WPF, and Windows Forms applications.


MVC is not a pattern specifically designed for the Web. However, a special case of the MVC pattern exists that was created for the Web. It is sometimes referred to as WebMVC or Model2. Whatever the name, the behavior is always the same. In a WebMVC model, there s a fourth actor that gets into the game: the front controller. Any request the user makes through the view is sent over as an HTTP request and captured by the front controller. The front controller determines which controller will actually handle the request and which method on the controller must be invoked to successfully and effectively service the request. The front controller invokes the method on the selected controller.


The selected controller is a class with a few public methods, each of which maps to a possible gesture the user may execute based on the user interface. The controller is also responsible for generating the new view either updating the existing view or switching to a new page.


Let s review the WebMVC pattern in light of the implementation provided by the ASP.NET MVC Framework.


What s the Model in ASP.NET MVC

In ASP.NET MVC, the model is any gateway you may have to the business logic. For relatively complex applications, the model is not even part of the MVC Framework, but it is something you already have available. For such applications, implementing an MVC means making the view and controller interact in a given way. For simpler applications, you create an ad hoc model using, for example, LINQ to SQL, Entity Framework, or just a bunch of manually written classes.


What s the Controller in ASP.NET MVC

In ASP.NET MVC, the controller is a class that contains public methods invoked from within the user interface. Public methods on a controller class are mapped to URLs using route tables in global.asax, as shown in Figure 1.


public class GlobalApplication : System.Web.HttpApplication


 public static void RegisterRoutes(RouteCollection routes)






     new { controller = "Home", action = "About", id = ""



 protected void Application_Start()





Figure 1: Route tables in the ASP.NET MVC Framework.


The {controller}/{action}/{id} string indicates the scheme of the URL that follows the server name. The name of the controller class is the first token, followed by the name of the method to invoke and optional parameters. You can have as many routes as you want to parse the controller name out of any URL format you want. Figure 2 shows a simple, but illustrative, controller class.


public class HomeController : Controller


   public ActionResult Index()


       ViewData["Title"] = "Home Page";

       ViewData["Message"] = "Welcome to ASP.NET MVC!";

       return View();



   public void FindAllCountries()


       TripsDataContext dc = new TripsDataContext();

       List<Country> list = dc.GetAllCountries();

       return new View("Countries", list);



Figure 2: A sample controller class.


There are two aspects of the controller you need to focus on: how the controller gets input data to process and how the controller produces and makes available return data. Internally, the controller interacts with the model and the underlying business logic to service the request. For example, the Find action in Figure 2 uses a LINQ to SQL data context to grab the full list of countries to display in the view. (Note that the ActionName attribute is supported only in Preview 5 of the ASP.NET MVC Framework.) The ActionName attribute allows you to use different names for the controller action and the method that actually implements it.


What s the View in ASP.NET MVC

The view in the ASP.NET MVC Framework is a plain ASP.NET page. However, this page is used differently than in any regular Web Forms ASP.NET application. In classic ASP.NET, any request from the user interface is targeted to a .aspx URL, which corresponds to a physical file on the Web server. In the ASP.NET MVC Framework, instead, the URL is a sort of message to the front controller (named as the URL routing engine in the ASP.NET MVC Framework). The routing engine parses the URL, determines the controller, executes the action, then locates the ASPX page to use as an HTML template to produce the expected response. In other words, the view in the ASP.NET MVC Framework is an HTML template that the controller uses to obtain the final HTML response.


The view is mostly made of raw HTML, along with some placeholders where fresh data can be injected. Placeholders are nothing more than old-fashioned, ASP-like code blocks, as shown in Figure 3. A couple of things in Figure 3, though, deserve more attention: the ViewData object and the HTML helpers.



 <% foreach (var country in ViewData.Model)

   { %>



      <%= Html.ActionLink("Edit", "EditCountry",

       new { id = country.ID } ) %>



      <%= Html.ActionLink(country.Name, "List",

       new { id=country.ID ) %>


 <% } %>


<hr />

<%= Html.ActionLink("Add New Country", "NewCountry") %>

Figure 3: A fragment of a view.


View and Controller

A controller action receives input from the URL. The content extrapolated from the URL is passed as arguments to the action methods. The runtime does this; all you care about is the signature of the action method. If you want to show details of a given customer, you first prepare a link in a page that points to a particular URL, such as


The URL contains the name of the controller (home) and the name of the action (list). The runtime environment resolves this URL invoking the method that corresponds to the List action on the HomeController class. What about arguments? In the controller class, you simply give the method all the arguments it needs:


public ActionResult List(int x, int y)





The URL will be modified as


With its proper input data, the controller does the job and retrieves any data it needs to display in the next view. How, then, is the view updated?


A controller method must return an ActionResult object. If a view must be created, the actual object returned is an instance of ViewResult (inherited from ActionResult). The View method on the controller class simply creates an instance of a ViewResult object. Let s consider the following:


// Assume this method is exposed by the HomeController class

public void Test()


  // Execute the action


  // Render the view

  return new View();



The View method on the controller class has a number of overloads for you to indicate various parameters, the most important of which are the name of the required view and data to fit in the view. By default, that is, when no argument is specified, the view is assumed to be an ASPX page located in the Views folder under a subfolder with the same name of the controller. The name of the ASPX file matches the name of the method. With respect to the previous code, the ASPX file will be a file named Views\Home\Test.aspx.


You also can indicate a different view file by setting the first argument of the View method to the name of the ASPX file. With the previous code, the view will be based on the HTML stored in the AnotherView.aspx file:


public void Test()


  // Execute the action


  // Render the view

  return new View("AnotherView");



As mentioned, the view is nothing more than an HTML template with some placeholders for data. The view is a class that inherits from ViewPage:


public partial class Test : ViewPage




The ViewPage class inherits from System.Web.UI.Page and adds a few extra properties, such as Html and ViewData. The former provides helper methods to emit predefined chunks of HTML in the view. The latter is the container through which the controller passes fresh data to the view.


The ViewData Container

The simplest way to pass data to the view is by filling the ViewData dictionary in the controller, as shown here:


public ActionResult Test(int x, int y)


  // Execute the action

  SomeResults obj = DoSomething(x, y):

  // Store results for the view

  ViewData["Property1"] = obj.Property1;

  ViewData["Property2"] = obj.Property2;

  // Render the view

  return View("Test");



Being a dictionary, you can fill ViewData with any .NET objects. Any value is associated with a string-based key. The content of the controller s ViewData dictionary is incorporated in the ViewResult object and is used to populate the view.


When created, the ViewResult object determines the ASPX page to use as a template and takes advantage of the ASP.NET Web Forms infrastructure to create a page class for the view that derives from ViewPage and incorporates the content of the controller s ViewData dictionary. As a result, you can have a view that contains fragments:



  <%= ViewData["Property1"] %>



Using ViewData directly is convenient as long as you have to generate simple HTML fragments. Let s examine the code you need for a hyperlink:


<a href=<%= ViewData["URL"]> <%= ViewData["Text"] </a>


As you can see, it is significantly less readable, as well as boring and error-prone to write. That s where HTML helpers fit in. The Html property on the ViewPage class contains several facilities to emit ad hoc HTML saving from dealing with the details of formatting. Here s how to emit a hyperlink using HTML helpers:


<%= Html.ActionLink(ViewData["Text"], actionName,

 new {param1=..., param2=...} ) %>


You specify the name of the action to execute and, optionally, the parameters to pass. The helper method will determine the correct URL to use.


Finally, you also can take advantage of a strong-typed version of the ViewData container. If you want to pass data to the view using a specific object be it a collection or a custom object you start by inheriting the view class from ViewPage<T>, where T is simply the type you want.


public partial class List : ViewPage<List<Country>>




The previous example shows a view class that receives a list of Country objects instead of an untyped dictionary of values. Here s the corresponding code in the controller method that calls the view:


public ActionResult List()


  // Load all countries

  List<Country> countries = new List<Country>();

  countries.Add(new Country { ID = 1, Name = "USA" });

  countries.Add(new Country { ID = 2, Name = "Italy" });

  countries.Add(new Country { ID = 3, Name = "Australia" });

  return View("List", countries);



As you can see, in this case you add the custom object as an argument to the View method. This step is not required if you limit the use of the untyped dictionary. Finally, in the view you retrieve this data as shown in Figure 3, using ViewData.Model instead of just ViewData.



Compared to classic ASP.NET, the ASP.NET MVC Framework requires a modified runtime environment and a different approach to programming. It forces you to see each page you must build as a collection of actions on some controller. The entire view is built to trigger HTTP requests based on made-to-measure URLs. The modified runtime environment, then, will resolve them properly to method calls.


As repeatedly said by Microsoft representatives at various conferences, the ASP.NET MVC Framework is optional and an alternative to classic ASP.NET. If you re not comfortable with it, then don t use it. However, make sure you understand an essential point: the ASP.NET MVC Framework is not the only way to add MVC (and hence, Separation of Concerns and testability) to ASP.NET applications. The ASP.NET MVC Framework is a specialized framework. Like it or leave it.


Dino Esposito is an architect at IDesign. He specializes mainly in ASP.NET, AJAX, and RIA solutions. Dino is the author of Microsoft .NET: Architecting Applications for the Enterprise (Microsoft Press, 2008). He also wrote Programming ASP.NET 3.5 Core Reference, also for Microsoft Press. Late-breaking news is available at




Hide comments


  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.