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

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 development – ‘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 code…
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

Don’t hate me for my .NET

I’m an outcast trying to fit in…

I’m an outcast trying to fit in… at an event like FOWA I’ll feel like working with .NET is akin to admitting to owning the Rednex single ‘cotton eye joe’ from the glory days of ’94… but then I’ll go to a Microsoft event and feel like a pariah obsessed with miniscule details that I shouldn’t worry about (unobtrusive javascript.. element ID and exact markup control…).

A generalisation this may be but it highlights the difference in perception between languages such as PHP/Ruby and .NET in the world of web. So much so that people often don’t even list .NET when they reel off examples after the phrase ‘your language of choice’.

I don’t so much want to ‘put the record straight’ just to put forward my experience starting out with PHP and moving to .NET, with a sprinkling of the stuff I usually hear against .NET.

Background

Following a pretty standard path I started out in web development with static HTML, moved on to being scared by CGI then dabbling with javascript and later some PHP and Actionscript (with some VB6 and Java studying thrown in there for good measure too). This led to my first full time role being as a PHP developer, which later evolved into a C# position.

.NET WebForms vs. Everyone Else

The first thing I (and many others) realise when moving to .NET (Webforms) is that it’s really not the same paradigm. In fact I’d go so far as to say that if you skipped straight to learning Webforms, you haven’t learnt web development. What you’ve learnt is winforms. And the reason for this is that that was the intention of Webforms – to assist winforms developers in making the leap to the web and to mask the lack of state.

The ‘innovation’ therefore of postback/viewstate persisted server controls was that as a developer you didn’t have to worry about working in a stateless environment as you did with other languages. Nor did you really have to worry about the actual markup output (in the same way that you wouldn’t worry about how the pixels rendered for a button in a windows app). Submit buttons and Select boxes can have server side Click and IndexChanged events and before you know it you’re well away without worrying about html or javascript or even css (if you went with some rather questionable attributes available on server controls for presentation).

What this caused however was a largely negative view of .NET from the non .NET side of the tracks, and it’s generally the sort of stuff I continue to hear.

However this is not an attack on .NET (whether people know it or not). This is an attack on a particular way of coding in .NET webforms. Yes, Microsoft pushed .NET to be used in those kind of ways but that doesn’t mean you had to do it that way.

In the same way that developers don’t use the visual interface of Dreamweaver to generate their markup .net developers don’t need to use server controls and viewstate. Just because it’s there and assists some people in their needs doesn’t mean everyone should use it.

Much of my recent work for example has relied heavily on generating Xml as the content and using Xsl to create the presentation, thus bypassing the majority of asp.net server controls and their associated scripts/viewstate/long ids.

Without taking this approach you can still make your own user and custom controls, but be smart about how you make them. Turn off viewstate when not needed, use standard html controls when you don’t need the functionality provided by an asp server control and use repeaters with your own standard html templates rather than .NET rendered gridviews.

.NET or not .NET?

It could be argued that doing these kinds of things is not ‘.net’ but thats not true. It may not be entirely ‘.net webforms’ but you are still using the power of the .net frameworks class library. You are still using the, in my view currently unchallenged awesomeness of, Visual Studio (and yes I’ve used eclipse.. it’s not as amazing as you might like to think) and you’re still getting the ability to write in the same language for your website, windows services, silverlight, xbox and windows applications.

Admittedly it’s unfortunate how long it has taken for the release of asp.net MVC (although lets be honest PHP weren’t flying off the blocks with full and complete OO support so no-ones perfect). However the key is, as with so many things, that the quality of your .net output is down to the quality of the development.

Wrap up

I too, when I was asked to swap to .net from PHP, thought .net was an overcomplication. “I want to just call the database and do a loop outputting html in my markup. I don’t want to put a GridView in the markup then in a ‘code behind’ ‘load event’ access the database and databind to the grid”.

It’s a leaning curve as with all things. My early PHP was, going back on it, messy to read and understand as it was all mixed in with markup with include files all over the place. Similarly my early .net work probably relied on an overuse of server controls. As you get in to something you get better at it. And although .NET seemed like a greater move away from static pages than PHP (which is probably why I saw it as an overcomplication) I now personally love working with it.

I’ll wrap this article up briefly with some reasons I like .net that either I haven’t found at all, or have found harder to do in other environments/languages.

  • Similar syntax to java/javascript/actionscript
  • Reusable classes across web applications, windows applications, windows services, IIS modules, xbox games
  • Very easy to cache with a large variety of inbuilt assistance
  • Extremely OO friendly

I’m not saying .NET is the best, or amazing, but its certainly not something to be looked down upon or avoided purely because it’s Microsoft or because of a misunderstanding surrouding it. Over the time I’ve been using it it’s got better and although the picture I paint in the intro to this article is still true, it is less so nowadays. Css Control Adapters have been around a long time to assist with poor rendering, MVC is upcoming, and along with things like ClientID mode the bad things are going or easily avoidable.

I’m not sure I’ve covered everything I would have wanted to in this post, as it is such a vast area and this was really just a one sided conversation from the POV of .NET not being quite as sucky as many people think. Please fire any points gripes or questions at me.

Mini Glossary (for those .net virgins among us)

One form to rule them all
Webforms asserts that each page has one form that contains all elements rather than multiple forms as and when necessary. Or to quote…

For example, most ASP.NET Web pages contain a single server-side Web Form, with multiple Web controls inside the Web Form. The Web Form is an HTML control (System.Web.UI.HtmlControls.HtmlForm). Those Web controls inside the Web Form are children of the Web Form.

Postback
Form field data is posted to the server and used to repopulate form field values automatically e.g. if you change an instance of a textbox server control before posting back .net maintains the value you posted from the first screen. Similar to the following manually achieved effect in PHP:

<textarea name="body" id="body" cols="40" rows="5">
     <?php echo htmlspecialchars(stripslashes($_POST['body'])); ?>
</textarea>
Viewstate
The encoded (and optionally encrypted) first hidden field used by .NET as a means to persist programatically set control properties.

<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTMwMTcxNDUyNmRk4HWhWoozWLYUelHWkPh3E67bXGo=" />

A control will gain its final value after the following cascade: Initial declarative value, Posted value from Request.Form (if postback), ViewState value (if changed via code after a postback).

Crazy IDs
Until the upcoming 4th version of .net developers were not trusted to know if there server control IDs were unique and because the built in viewstates, postbacks etc relied on it someone decided to make damn sure that control IDs were unique and context based on their location in the control heirachy. This led to ids like “ctl00_asp_menu_links_ctl03_contextLink”. Which, if someone added a parent or reshifted markup slightly, would change. Particularly helpful for clean client side development.

This post was written by Craig Rowe, developer at Headscape. For more posts from Craig visit his blog.