MVC 4 – An Introduction

I’ve started looking at the MVC 4 platform for developing web sites in ASP.NET, so I’ll record my experiences as I go along.

First, an introduction to the ideas behind MVC would be useful.

MVC stands for Model-View-Controller, and is a popular design pattern used in structuring medium to large programs. Its use is not restricted to ASP.NET or to web development; in fact it’s something of an industry standard for many software development projects.

The concept is fairly simple, and is based on the idea that the main functions within a program should be separated, since this makes it easier to assign different people to different tasks, as well as making the code easier to understand and maintain.

In many programs, there is a collection of data which can be viewed in various ways. For example, in a word processor, the data consists of the text and images contained within the document. This data can be viewed in various ways: in edit mode where changes can be made, in print preview mode where the user sees what the document will look like when printed, in outline mode where only the section headers are shown, and so forth. In all these views the underlying data – the model – remains the same. Thus to put it simply, the model is the information stored in a program and the view is how it looks to the user.

The controller is a bit more vague, but in essence it’s the code that links the model to the view. In a program with various user interaction controls such as buttons and menus, the controller consists of the event handlers that process the user’s actions. For example, if the user presses the Print Preview button in a word processor, the controller processes this action by retrieving the document from the model and passing it to the view that displays a print preview.

In the particular case of MVC as applied to ASP.NET (rather confusingly, MVC can refer to the generic design pattern as used in any type of program and also to the specific implementation in ASP.NET), the model stores the data (in C# data structures or possibly in a database) and the view generates the HTML which allows the user to view the data in some form. The controller responds to a user’s request for a web page by retrieving whatever data is required from the model and then passing this to a view which constructs the web page that is sent back to the user.

That’s really about all you need to understand about MVC to get started. From here on, it’s easiest if we use an actual example to demonstrate how to build an MVC project. In what follows, I’m using Visual Studio 2012 (version 11 of Visual Studio), which has support for MVC 4 built in. If you’re using VS2010, you’ll need to download and install MVC 4 support as an add-on. This should be freely available from Microsoft’s web site – as always, Google is your friend here.

Even in VS2012, however, the first time I tried to create an MVC 4 project, I got an error saying that the NuGet package wasn’t found. This is easily fixed by visiting nuget.org and installing the package.

Assuming you’ve got VS set up properly, begin by creating a new project. In the New Project dialog, select ASP.NET MVC 4 Web Application. We’ll look at building a web site for a comic shop, so call the project ComicShop and click OK. You’ll then see the New ASP.NET MVC 4 Project dialog, which offers several options for your new project. Internet Application is pre-selected, and if you go with this you’ll get the outline of a functional web site with pages for creating accounts, logging in and so on. All of this functionality can be a bit daunting at first, so we’ll start with the Empty template.

Even with an empty project you get a fair number of files. In Solution Explorer, have a look at the folders that have been created; you’ll see among them folders for Controllers, Models and Views and as you might guess, that’s where most of your work will be done.

If you try running the project at this point by pressing Control+F5 to start without debugging, what should happen is a page will open in your default browser (I use Google Chrome, but this should work with whatever your default browser is). Visual Studio will start up a local web server for the purposes of testing your project and attempt to display the home page of this site in the browser.

At this stage you’ll get an error message saying the the page at ‘/’ (the root of the web site) couldn’t be found. This isn’t terribly surprising, since we haven’t added any pages to the site yet.

So where do we start? First we need to understand a bit about how MVC handles naming conventions. The conventional name for a controller class is <Path>Controller, where <Path> is the part of the URL following the site’s address. For example, with the local server created by VS, the home page might have the URL localhost:30844/Home/Index. In this case, the controller class that handles the request for the page is HomeController. (We’ll deal with the Index part in a minute.)

Let’s add a controller to the project in an attempt to get a home page. In Solution Explorer, right-click on the Controllers folder and select Add –> Controller. In the dialog that appears, name the controller HomeController and select Empty MVC controller for the template, then click Add. You’ll see the file HomeController.cs appear in the Controllers folder, and the class file will be displayed in the code editor. It should look like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ComicShop.Controllers
{
    public class HomeController : Controller
    {
        //
        // GET: /Home/

        public ActionResult Index()
        {
            return View();
        }

    }
}

Before we explain anything, try running your project again. You’ll still get an error, but this time it’s complaining that it can’t find a view. To fix this, right-click on the Index() method and select Add view. Accept the default name of Index and click Add. You’ll see another file appear in the code editor, but ignore that for now. Now try running the project again.

This time, you should get a page in the browser with the word ‘Index’ in a big, bold font at the top. Congratulations – you now have a functioning web site! OK, it’s not particularly informative, but it’s a start.

Now for a bit of explanation as to what has happened. The most obvious question is probably: How did the web server know to display the page with Index on it? After all, we could have called our controller anything at all, and not just HomeController, and we never specified Home in the browser – the page just magically appeared.

Actually, if we had called the controller something else, it wouldn’t have worked. To see why, look in Solution Explorer and open the folder called App_Start. Inside this, open the file RouteConfig.cs. You’ll see this code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace ComicShop
{
  public class RouteConfig
  {
    public static void RegisterRoutes(RouteCollection routes)
    {
      routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

      routes.MapRoute(
          name: "Default",
          url: "{controller}/{action}/{id}",
          defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
      );
    }
  }
}

The routes.MapRoute() call defines what the default URL will be. The ‘url’ parameter says that the default format for a URL is “{controller}/{action}/{id}”, and the ‘defaults’ line says the default controller name is Home and the default action name is Index. The last entry says that ‘id’ is optional.

What this means is that if we don’t specify a URL, the request to the server is taken to be for the page /Home/Index, and that the controller called HomeController should be called for this. Within this controller, the action called Index should be called. (The ‘id’ is an optional bit of information we can tack on to the URL, but more on that later.)

What is happening, then, is that the server is started up and looks for a controller called HomeController and then for an action called Index within that controller.

That action, at the moment, returns the result of a call to View(), and as you’ve probably guessed, that uses the code in the Index.cshtml file that you created above when you added a view to the Index() method to generate the HTML which is sent back to the browser. If you know a bit of HTML syntax, you’ll see that all this page does is print Index, which is in fact what you’ve seen.

Advertisements
Post a comment or leave a trackback: Trackback URL.

Trackbacks

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: