Home > .net 3.5, LINQ, Microsoft, MVC, Visual Studio 2008 > The .NET MVC Framework – Part 1 – Introduction

The .NET MVC Framework – Part 1 – Introduction

December 17, 2007

This is the second post in the series discussing new web development frameworks that have come out in the past few weeks and revolve around the Microsoft .NET development platform.

#1 – Microsoft Live Labs Volta

Microsoft .NET MVC Framework

The .NET 3.5 Extensions Package that just hit CTP added in a bit of new functionality—the Microsoft .NET MVC Framework.  ScottGu has several great posts about the MVC and a neat four part exercise on connecting to the Northwind Database and hashing out a product list.

For those unfamiliar with the MVC Framework, you may already be doing this to a degree.  The MVC (modal-view-controller) pattern is an architectural pattern used to separate the entity model of your application (the business objects and logic or the modal) from the user interface (the view) through the use of a controller.  Be careful not to confuse the model as strictly a data model—it’s more than that, it’s the model of your both the data itself and the business logic that goes with it.  With this, it’s possible to totally remove the presentation aspect of your design and implement tests more efficiently.

InformationImportant: For more of a historical view of the MVC pattern, check out this article.  It’s pretty interesting (even though it’s in Java, which is where I first learned of the MVC pattern).

For my example, I’m going to work on implementing a new version of the WebStorage web site (http://photos.tiredstudent.com).  I’ve got a v3.5 standard prototype in the works, but this will help demonstrate both how a working application goes together with existing data AND how the tools work (plus, I’m really tired of demoing with the Northwind or AdventureWorks databases).

I’ve broken this up into several parts I’ll be writing over the next couple of days.  Quite frankly, the posts ended up being REALLY long.  I had planned to do a screencast of this (and still might)—I just need to get my hands of Camtasia (maybe Santa will come early).

These posts also take into consideration you’ve:

It’s not productive for me to totally reproduce what Scott has—so I’ll be taking in bits and pieces from everywhere.  I plan to include a bit more on unit testing (with Rhino Mock examples from Phil Haack), the odds and ins that have come up in creating the MVC apps, and how this compares to WebForms.

ImportantWarning: The Extensions Package is currently a preview—there are known glitches (which I’ll note when I find them) and general strangeness that can occur.  I don’t recommend pushing out a full MVC project to production right now, but it doesn’t hurt to experiment and become familiar with it.  Also, when in doubt, check out the MVC Forums on asp.net.  I’ve been reading through them daily and found several very helpful posts.

Creating a MVC Project

To begin, you’ll need to install the extension package.   I also recommend downloading Rob Conery’s MVC Toolkit—the extension methods in it will be used in this demonstration and are VERY helpful.

The best place to start is by creating a new “ASP.NET MVC Web Application and Test” solution.  This template adds both the MVC Web Application and a Test application into your project—with the correct libraries and dependencies already added.

Selecting the MVC Template

The downfall to this template?  Everything is named MvcApplication—kinda annoying that it doesn’t pull up the name of the solution and go with that—a changing that will hopefully be implemented soon.

The default solution structure is pretty simple—folders for each component of the project.

Solution structure of basic MVC Framework project.

InformationImportant: Before we get started, I recommend setting a “Specific Page” start action for your project?  Why?  We want to be sure we invoke the MVC framework—not specific .aspx pages when we’re testing our application.  This way, we can specify a “path” and each time we debug, we’re good to go with that path. As you can see below, since our application will have a default path of / (that, as we’ll see, / routes to our Home controller) , we’ll use that.  To get to this screen, right click your Web project | Properties | Web tab.

Setting the home page.

Preparing Our Default Routes

To start off, I really like how Phil Haack has setup routing—by pulling the routes out of the Global.asax and dropping them into a new class called RouteManager that sits in the root of the web application project. 

Before I found this post, the whole idea of cluttering up the Global methods really smelled to me.  Good call.  It’d be great if they’d simply add this to the templates.

public static class RouteManager

{

public static void RegisterRoutes(RouteCollection routes)

{

Type defaultRouteHandler = typeof(MvcRouteHandler);

 

routes.Add(new Route

{

Url = “[controller]/[action]/[id]”,

Defaults = new

{

action = “Index”,

id = (string)null

},

RouteHandler = defaultRouteHandler

});

 

// IIS 6.0 Router

routes.Add(new Route

{

Url = “[controller].mvc/[action]/[id]”,

Defaults = new

{

action = “Index”,

id = (string)null

},

RouteHandler = defaultRouteHandler

});

 

routes.Add(new Route

{

Url = “Default.aspx”,

Defaults = new

{

controller = “Home”,

action = “Index”,

id = (string)null

},

RouteHandler = defaultRouteHandler

});

}

}

As an addition, I have added a defaultRouteHandler to my RouteManager.  Typing “typeof(MvcRouteHandler)” over and over again and, maybe in the future, changing it is a bit annoying.  My hope is that the attribute goes away and/or becomes optional.  I shouldn’t need to specify the default value.🙂

Now, in the Global.asax, I can simply call  

RouteManager.RegisterRoutes(RouteTable.Routes);

to prepare my routes and the same in my unit tests—cool.

Preparing our Master Page

I’ll get into formatting a bit later (or I’m sure you can come up with designs FAR better than mine), but the Shared MasterPage does need a bit of work.

To open the shared master page, which is essentially a shared master “view” page, look under Views | Shared.

The Master Page controls our style sheet, navigation, and headers—but you can rip these out and put your own in… you are not limited to the master page provided.  It works well, however, for demonstration purposes.

By default, our menu has two options—Home and About Us.

<div id=”menu”>

<ul>

<li><a href=”~/” runat=”server”>Home</a></li>

       <li><%= Html.ActionLink(“About Us”, “About”, “Home”) %></li>

</ul>

</div>

I prefer things to be consistant and don’t like the hardcoded URL left in there; we can easily replace it with an Html.ActionLink.  (Click here to read more about the ActionLink extension method).  In addition, we’ll need one more: the Galleries home page.

The order of the ActionLink parameters is “Link Text”, “Action”, “Controller”.  We don’t have a Galleries controller (or an Index action in that controller) yet, but we’ll get there.

<ul>

<li><%= Html.ActionLink(“Home”, “Index”, “Home”) %></li>

       <li><%= Html.ActionLink(“About”, “About”, “Home”) %></li>

       <li><%= Html.ActionLink(“Galleries”, “Index”, “Galleries”) %></li>

</ul>

If we view our page in the browser and click Galleries, we can verify that the link is indeed trying to send us to /Galleries (and we haven’t implemented that yet).

Galleries controller view -- not yet implemented.

Implementing a New Controller and View

We’re ready to implement a new controller and view for our gallery application.  This new controller will handle viewing our galleries and their contents. 

Most likely, we’ll have two actions and according URLs will be:

  • Index (showing a list of galleries)
  • /Galleries
  • Show (showing the contents of a specific gallery)
    • /Galleries/Show/##

    Looking at the Show action of our Galleries controller, you can see the route pattern we created above.  [Galleries]/[Show]/[##] == [Controller]/[Action]/[Id].

    To create a new Controller, right click on your Controllers folder and Add New Item. 

    New MVC File Types

    As you can see, there are several new MVC file templates available.  This time, we want a MVC Controller Class.  I’ll name it GalleriesController.

    InformationImportant: It’s important to note that naming conventions are very important with the MVC Framework templates.  Since I’m naming the controller GalleriesController, the framework will automagically assume that the views for this controller are in the “Galleries” directory and attempt to find them there.  Be sure your names for ___Controller match the file heirarchy of your views.

    Our new GalleriesController contains one method: Index.  The Index method is typically our default page action and, according to our routing rules, is the action that fires if we browse to /Galleries or /Galleries/Index or /Galleries/default.aspx.

    We want to render a new View, which we’ll create in a moment, called Index.  We’re not passing any information to the new view (we’ll get to that later)—simply rendering it.

    [ControllerAction]

    public void Index()

    {

    RenderView(“Index”);

    }

    This creates a link between an action in a controller and a specific view to be rendered.  Remember, as I noted earlier, “Index” needs to be in a specific location—in this case, under /Views/Galleries.

    I’ll create a new directory under Views called Galleries to hold the Galleries view templates.  Inside this directory, I want to “Add a New Item” again; however, this time, add a MVC View Content Page.

    The Content Page gives us the option to specify a MasterPage, which we want to select /Views/Shared/Site.Master.  Be sure not to choose MVC View Page as you’ll simply get a standard page and need to add in the placeholder information manually.

    Views heirarchy.When finished, the Views heirarchy should look similar to the image on the right. 

    Again, it’s important to keep the Views matching the name of the controllers.  If you have a controller called CustomersController; you’d have a Views directory called Customers.

    After adding in a quick header to the Index page, we can browse to our site, click Galleries and see our new view page.

    Galleries Controller view.

    Now, we’re ready to add the galleries catalog and begin pulling in some data. We’ll do that next time!

    %d bloggers like this: