Skip to main content

Why You Should Consider MVC 2 for Your Next ASP.NET Web Site

You have many choices when you set out to design a new web site. Some people might say that you have too many choices. For the purposes of this article, I'm going to assume that you've already decided that you're going to use ASP.NET in one form or another, so won't presume to debate the merits of Windows versus Linux hosting. Instead I'm going to focus on a real project where we chose MVC Release 2 for a redesign of an existing ASP.NET WebForms site.

There are four main reasons that helped us decide on using ASP.NET MVC for our project:
  • Testability
  • Clean, SEO-Friendly URLs
  • Full Control of the HTML generated
  • We got to delete a lot of code!
Testability
By default, MVC projects encourage the practice of test-driven development. Each controller can be paired with a controller test class that exercises the controller's functionality without regard to the view that will ultimately render in the UI. Testing each controller's methods in this way ensures a clean separation of UI and logic. Done correctly, it is possible to build a UI layer with absolutely no code-behind (which isn't supported in a MVC project in the first place).
Clean, SEO-Friendly URLs
Let's face it. URLs that look like this are so last decade!

Plus, from a practical point of view, the above URL isn't very search-engine friendly. Search engines tend to ignore the query string in a URL (everything after the question mark). Thus, in the above example, search engines would treat all the URLs to years' worth of articles as the exact same link. This is not good if you want your articles to be found.
A better choice would be to allow URLs like this:
http://eleganceincoding.blogspot.com/2010/05/

Using this method, each of your articles would have a unique URL. Each article would thus be individually indexed by search engines. It can be made better, still. Imagine if someone were to bookmark the above URL so that they could come back to the article later. It's not very human-readable, and months later, may not mean much.
Consider instead the following URL:

This URL is both search-engine friendly and human friendly. Humans can look at the URL and know immediately what the article is about. Search engines can often do the same. With the term "mvc" in the URL (and presumably the title and body of the page), how much more relevant will the page appear than the prior URL?
Until recently, creating this type of URL required a technique known as URL rewriting. The web server would parse the URL into pieces, usually using regular-expression matching, and then change the URL to look more like the first example above.
ASP.NET MVC uses a routing engine to manage the URLs, and no rewriting actually occurs. Instead, the routing engine processes the URL and determines which action method to call on the appropriate controller.
This means that the URL http://eleganceincoding.blogspot.com/2010/05/why-choose-mvc-2-for-your-next-aspnet.html might be processed by the ASP.NET routing engine to call the following method on the ArticleController class:
public ActionResult Display(int year, int month, string title)

The really cool thing about this strategy is that the article title can exist solely for the benefit of bookmarks and search engines, and then totally ignored by the controller. It can simply continue to look up the article by year/month. Of course, that assumes you only have one article per month. Another great thing about these routes is that you can change them practically on the fly, say to add an article ID, and the framework will automatically adjust. I'll touch on routing basics in a future article.

Full Control of HTML Generated
One of the (many) criticisms of Web Forms is the lousy HTML generated by the ASP server engine, particularly if you want to use a pure CSS-based layout. Recent versions of Web Forms have addressed this shortcoming, but if you want absolute and total control over your HTML, it's hard to beat the clean pages you can create within the MVC framework. We managed to build 100% tableless CSS-based layouts in our project, with no ViewState. I'll touch on that in more detail at a later time.

We Got to Delete a Lot of Code
One of my favorite development pastimes is refactoring. Due to its inherent testability, ASP.NET MVC makes it easy to refactor your code. So if you decide that there may be a better way to do something, go ahead and try it. Your tests, if well written, will help you remain confident that you haven't broken anything.

The best type of refactoring is when you get to delete huge bloated sections of code and replace it with almost nothing. My favorite example is one web page that simply displayed a specific record from the database for the user to edit. The original Web Forms .aspx page and its accompanying code-behind file were literally hundreds of lines long. There was code to handle localization of form labels, pre-processing of data prior to its display, server-side validation, calls to the database, and a lot of event handlers.

By the time I was finished, the entire page had been separated into two action methods on the controller, with fewer than a dozen lines of code between them. The View that generated the HTML form to the user ended up being 33 lines, including whitespace and comments. Now that's what I call deleting code! Less code is a good thing. Small classes and method are dramatically easier to test and maintain than large classes.

Later, when I discuss views and view models in more detail, I'll explain how this was all possible.

Pulling It All Together
One thing that I'd like to point out is that when building an MVC site, the page URL and the action method tied to it, are completely decoupled from the UI that will actually be displayed to the user. Although it is possible for an action method to return HTML, it's not considered a best practice. So I won't even discuss it here.
Instead, the Display() method returns an ActionResult, which is a special object in ASP.NET MVC. The default implementation of any action method is to return a View object. In fact, when you first create an action method in Visual Studio, the auto-generated method will look like this.
public ActionResult Display()
{
   return View();
}
Believe it or not, this amount of code is all you need to get something to display in the web browser, assuming you create a view called Display.aspx. But I'm getting ahead of myself.

Comments

Popular posts from this blog

How to copy your Frozen Free Fall progress to a new phone

It's happened to all of us. You are about to get a branch new smartphone, when it hits you. You're on level 250 of Frozen Free Fall. If you get a new phone, you'll lose all of that progress! Ok, admittedly this isn't the most pressing problem of our time, but it's annoying. So today I decided to do something about it.

I have a Samsung Galaxy S4 (Android), and just received an iPhone 5c. Before you bash me on my phone choice, let me explain that the iPhone is provided by my employer at no cost to me. Now you may proceed to bash me for putting games on my work phone. 
First step: Frozen Free Fall had already been installed on both devices. Next, using the Astro File Manager on my Galaxy, I searched and found the Frozen game save stored in /storage/sdcard0/Android/data/com.disney.frozensaga_goo/files/user.dat. I imagine it will be in the same location on any Android phone. If not, just look for user.dat in a folder with a similar name. So, using a USB cable and the A…

Ionic vs. Bootstrap - for a Web App

Ionic 1.x vs Bootstrap 3.x for a Web AppI was recently asked at work to come up with a comparison between Ionic Framework and a more traditional Angular/Bootstrap combination to create a web app. The application will primarily be used in a desktop web browser (probably Chrome or IE). There are also some use cases where it will be accessed from Safari on an iPad. However, this is purely a web; there are no plans to install the app onto the iPad as a hybrid app. Thus, recommending Ionic to build the UI hadn't occurred to me until the request was made.

This is even more surprising in that I recently published a Pluralsight course on Ionic Framework 1. It should have been the first thing that crossed my mind.
One constraint is that currently only Angular 1.x and Bootstrap 3 are authorized web technologies. Ionic 1.3 was recently approved, but not Ionic 2, Angular 2, or TypeScript yet.
Given those constraints, herein is my attempt at coming up with reasons to use (or not to use) Ionic…

Record Video of Your Android Screen on a Mac with ADB

Background I've been working a lot lately on writing mobile apps using the Ionic Framework. My goal is to be able to release apps for both iPhone and Android at roughly the same time. So far, I've only released apps for Android, simply because I'm too cheap to pay Apple $99/year. But that's neither here nor there.

The Problem Today I wanted to record a demo video for one of my apps running on my Android test device, an older Samsung Galaxy S4. I had no idea how to do that. Camtasia 2 for the Mac supports iOS devices out of the box, but not Android. What to do?

After a bit of searching, I found instructions on a few different sites. None of them had all of the steps I needed. So rather than trying to remember where I found everything, I figured I'd put all of the instructions in one place on my own blog so I could find it again easily.
PrerequisitesAndroid Debugging Bridge or Android SDKUSB to Micro USB cable (preferably the one that came with the device). Record t…