Skip to content

A podcast for those who design, develop and run websites.

Boagworld is the blog of web strategist Paul Boag who lives in the heart of rural Dorset (hence the cows). He produces a weekly podcast with UX consultant Marcus Lillington on building and running websites. They also run the web design agency Headscape.

Latest Shows

203. Why your blog fails
This week on boagworld: the secret of successful blogging, will Google personalisation affect your sites ranking and how to help users too busy to read.
202. Rocket Surgery Made Easy
This week on Boagworld: Steve Krug on monthly usability, Steve Marshall talks about form design and Paul rejoices over the new era for browsers in Europe.
201. Are clients stupid?
This week on Boagworld: We review the freelancing book Noded, discover a new web tool called 'Support Details' and Paul tells us all a story.
200. A taste of the show
This week's show gives you a taste of the live 12 hour marathon that took place to celebrate the 200th Boagworld.
199. Time to generalise
This week on Boagworld: The changing role of web designers, Colin Firth on content and Becky Jones talks about the changes at Google.

or view all shows

Have your say

Become a part of the Boagworld community...

Why .NET MVC? (and why should we Care?)

Posted in Tech/Development on: Tuesday, August 18, 2009 by Craig Rowe

Having previously written about the highs and, perhaps more importantly, lows of working as a .NET developer. This article will continue the trip into Microsoft World, only this time it’s to the land of MVC.

Recently Microsoft was brought back to the attention of many, not just for the interestingly named Bing, the Yahoo ‘partnership’, or the delights of a browser
choice screen
. Developers with their ear to the Redmond ground became aware of something being touted as the next big thing for Microsoft .NET – ‘MVC’.

Although announced some time ago many users left it aside until a more complete release. Now however, with another release on the horizon and many examples of sites that use MVC (including the particularly well known StackOverflow) it is certainly something people are using on a daily basis.

As would any eager developer I tried the beta, had fun installing the final release and have now been involved working with and using it. My impressions so far are good. It would appear that Microsoft have addressed those amongst us bemoaning the issues of WebForms. For example lets take a look at a collection of comment snippets from the “don’t hate me for my .NET” post:

Markup

When I first tried the winforms model after being an ASP developer for many years part of me loved it’s rapid development but I always felt a bit dirty when looking at the source
Chris Morledge

A key point really here is that the abstraction that was provided by .NET webforms was/is, for some, a step too far. The masking of actual html output behind server controls, although rapid, caused friction between backend and front end developers. A carefully crafted html design would often be bounced back and forth as developers implemented using controls.

Conversely MVC is far closer to the metal in terms of both your html and indeed your required knowledge of the way the web works. Although views are often output with html helpers these are far easier to customize than creating your own Custom Control Adapters. With .NET MVC, webforms Developers will be reminded that there is no inherent state on the web (and perhaps hopefully of the separation between back and front end development – I’ve never been a fan of auto-generated javascript. It can lead to an over reliance and ignorance of approaches like hijax).

Tutorials Available

All of the training material and tutorials will show you how to do it the easy way
Tim Snadden

This has been an issue I’ve had with some Microsoft materials for a long time. Reading about things like <asp:SqlDataSource /> controls always left a bad taste in the mouth in terms of reusability, testability and layered architecture. However, some of the materials on the MVC site are bucking that trend.

Working around .NET

we crafted our own pseudo MVC framework
cmv

Similarly to cmv many devs have crafted their own implementation to separate presentation and logic concerns. I have previously discussed using XML and XSL for this. However now we don’t have to, or if we do want to with .NET we can at least work from an open source framework (yes MVC is on an open license) with a multitude of available view engines or even create our own view engines.

Seemingly few people who dislike the idea of using Microsoft technologies are aware of the Mono Project. An open source .NET implementation with an IDE (Mono Develop). For those of you who would like to know more I thoroughly recommend Miguel de Icaza’s appearance on the stackoverflow podcast. Mono is also not as open to legal attack from Microsoft as people may think.

So how is it done?

There are already many resources for learning .NET MVC, not least the asp.net/mvc site itself. In brief a project will contain:

Views

- Implementing IView (guaranteeing a Render() method)

The default MVC project from Visual Studio includes a number of sample views. These are instances of the ViewPage class. Data can be passed to these views by the controller through the ViewData property bag. However if you change the type to ViewPage<T> these views become typed views. For example you may have a ‘CustomerViewModel’ object (encapsulating view related information for a Customer entity/Customer BO) and so create a ViewPage<CustomerViewModel>. In this case the View has access to a ViewData.Model which will be a typed customer view model instance.In terms of team breakdown these ‘.aspx’ pages will be where the html is and where designers may wish to make their mark.

[csharp]
<%@ Page=”" Title=”" Language=”C#”
MasterPageFile=”~/Views/Shared/Cargowire.Master” Inherits=”System.Web.Mvc.ViewPage<IEnumerable<BlogPost>>” %>
[/csharp]

fig. 1.0

Controllers

- Implementing IController (guaranteeing an Execute() method) or generally inheriting from the Controller class

The Controllers job will be to direct the traffic based upon the request, including processing actions (using methods that return ActionResult)
that map to the ‘action’ url part. [csharp]
// GET: /Home/
public ActionResult Index()
{
… // e.g. Commands to return an IEnumerable<BlogPost>

// returns ViewResult(IView) (Ultimately inherited from ActionResult)
return View(blogPosts)
}
[/csharp]

fig. 1.1

Models

- Component(s) for maintaining state

Models can take many forms including business objects mapped to sql through linq to sql
or of course a number of layers including services, repository and business object classes.

Routes

- defined in Global.asax

[csharp]
routes.MapRoute(
“Default”, // Route name
“{controller}/{action}/{id}”, // URL with parameters
new { controller = “Blog”, action = “Index”, id = “” } // Parameter defaults
);
[/csharp]

fig. 1.2

The Process

Figures 1.0 – 1.2 illustrate a simple example using .NET MVC. In this example a route has been defined for the blog controller and the action ‘Index’. When a site visitor hits ‘http://site.com/blog/index’ the .NET MVC Framework will invoke the Blog Controller’s Index method. This method will ultimately retrieve an IEnumerable<BlogPost> instance which can then be displayed within the typed view. For example the view content could be:

[csharp]
<% foreach (var post in Model) { %>
<div>
<h2><%= ViewData.Model.Title %></h2>
<p><%= ViewData.Model.Body %></p>
</div>
<% } %>
[/csharp]

fig. 1.3

In this simple example the BlogPost class is a business object that could well map directly to a persistant storage entity. However in a more fleshed out system it could be that the View is typed to a ‘BlogPostsViewModel’ that contains items that can be enumerated for listings, plus items for category description etc.

Final Thoughts

This article has attempted to do two things. Firstly to act as a sequel to “Don’t Hate me for my .NET” but secondly to introduce, at a basic level, .NET MVC. The example given is to provide a flavour of MVC development on the .NET platform and could be expanded to cover a number of other currently favoured approaches and technologies including more detailed assessment of the Model and how the dependencies interact.
However, that may be for another day.

The community around .NET MVC is already thriving with a plethora resources, many of which I have linked to when possible above.

Sources / Related Links

What did you think about this post?

5 Comments

Comments are for the discussion of this post. If you have other questions / comments then post them to the forum or send me an email

  • We’ve been using ASP.NET MVC in a commercial app for a couple of weeks now and just love the clean separation of concerns it gives you.

    The ASP.NET MVC futures project has some nice overloads that let you keep strongly typed urls in your views too. This makes mistyping hyperlinks much harder to do.

    Nice summary article Craig!

  • Mike Ormond says:

    Great post Craig. I think you cover most of the concerns people have with the Web Forms model (though I feel obliged to point out that many people also use it very successfully day-in, day-out to build great web applications :) ).

    ASP.NET MVC has gathered great momentum in a relatively short space of time, not least because it’s so extensible. Don’t like testing framework xyz? That’s okay. Don’t like our view engine? That’s okay. And of course, as you point out, the source for ASP.NET MVC is available under an open source licence.

    Allow me to correct your link to the official ASP.NET MVC page which should of course be http://www.asp.net/mvc. Also of interest, Scott Guthrie recently blogged about the features we can expect to see in ASP.NET MVC V2 http://weblogs.asp.net/scottgu/archive/2009/07/31/asp-net-mvc-v2-preview-1-released.aspx.

    • Craig Rowe says:

      Hi Mike, Cheers for taking the time to read.

      I agree WebForms is a powerful approach for many and .NET MVC is, in my eyes, definitely an alternative as opposed to a replacement.

      Thanks for providing the correct asp.net/mvc link it must have got mixed up in the copy to wordpress. I tried to stuff in as many further info links as possible for the interested reader. Both Scott Gu and Phil Haacks site are excellent resources for keeping up to date and I’d recommend them to all.

  • Tim says:

    This article reads like MVC is a new concept altogether, as well as new to .NET. I think it would be great to hear how .NET MVC stands up against other MVC-enabled frameworks, such as Ruby On Rails, Struts and Symfony…

    Other than that, a well written article.

    • Craig Rowe says:

      Cheers Tim,

      I had tried to refer to it as .NET MVC as much as I could. I wouldn’t want to misrepresent MVC as some kind of recent Microsoft invention! I agree with you that it would definitely be good to get some more comparison based content up. This first one just was intended as an intro to the .net implementation. Hopefully we’ll see some more developer content in the future.

Leave a comment

Additional Information

Produced by Headscape

Boagworld is produced by the web design agency Headscape founded by Marcus, Paul and Chris Scott. Headscape also has a number of other talented guys who blog. Check them out.

  • Craig Rowe is one of our amazing developers and writes some superb posts on everything from .net to AIR apps.

  • Ed Merritt is a Headscape designer who's blog contains examples of his work and a number of free Wordpress themes.

  • Dave McDermid is a Headscape developer who has an excellent blog. He blogs on everything from AJAX to security.

  • Rob Borley is one of our project managers and blogs regularly on client and project management issues.

  • Leigh Howells is our multimedia design guru (whatever one of those is). He blogs on a mixture of design and music.

Paul elsewhere

Paul just can't shut up. He publishes regular audioboos, has a personal blog and is addicted to twitter. He also writes and speaks regularly. Check out the most recent below: