Chapter 2. Model-View-Controller and ASP.NET

Model-View-Controller (MVC) has been an important architectural pattern in computer science for many years. Originally named Thing-Model-View-Editor in 1979, it was later simplified to Model-View-Controller. It is a powerful and elegant means of separating concerns within an application (for example, separating data access logic from display logic) and applies itself extremely well to web applications. Its explicit separation of concerns does add a small amount of extra complexity to an application's design, but the extraordinary benefits outweigh the extra effort. It has been used in dozens of frameworks since its introduction. You'll find MVC in Java and C++, on Mac and on Windows, and inside literally dozens of frameworks.

Understanding the core concepts of MVC is critical to using it effectively. This chapter discusses the history of the MVC pattern, as well as how it is used in web programming today. You'll also learn some of the limitations of ASP.NET Web Forms and how ASP.NET MVC attempts to release the developer from those limitations.

WHAT IS MODEL-VIEW-CONTROLLER?

Model-View-Controller (MVC) is an architectural pattern used to separate an application into three main aspects:

  • The Model: A set of classes that describes the data you're working with as well as the business rules for how the data can be changed and manipulated

  • The View: The application's user interface (UI)

  • The Controller: A set of classes that handles communication from the user, overall application flow, and application-specific logic

This pattern is used frequently in web programming. With ASP.NET MVC, it's translated roughly to:

  • The Models are the classes that represent the domain you are interested in. These domain objects often encapsulate data stored in a database as well as code used to manipulate the data and enforce domain-specific business logic. With ASP.NET MVC, this is most likely a Data Access Layer of some kind using a tool like LINQ to SQL, Entity Framework, or NHibernate combined with custom code containing domain-specific logic.

  • The View is a dynamically generated page. In ASP.NET MVC, this is implemented via the System.Web.Mvc.ViewPage class, which inherits from System.Web.UI.Page — more on that in Chapter 6 when you dig into Views.

  • Finally, the Controller is a special class that manages the relationship between the View and Model. It responds to user input, talks to the Model, and it decides which View to render (if any). In ASP.NET MVC, this class is conventionally denoted by the suffix Controller.

You'll dive more into where each of these classes lives, and why, further along in this book.

MVC ON THE WEB TODAY

For many, the Web didn't really become prominent until the first graphical browsers began to flood the market, starting with Mosaic in 1993. Shortly after, dynamic web pages began showing up using languages such as Perl and enabled by technologies like the Common Gateway Interface (CGI). The technology available in the early stages of the Web was focused more around the concept of scripting HTML to do light, content-driven work, as opposed to deep, application logic, which just wasn't needed back then.

As the Web grew and HTML standards began to allow for richer interactions, the notion of the Web as an application platform began to take off. In the Microsoft realm, the focus was on quick and simple (in line with the simplicity of VB), and Active Server Pages (ASP) was born in 1996.

ASP used VBScript, a very simple, lightweight language that gave developers a lot of "unprescribed freedom" in terms of the applications they could create. A request for an ASP page would be handled by a file with the .asp extension, which consisted of server-side script intermixed with HTML markup. Being a procedural language, many ASP pages often devolved into spaghetti code in which the markup was intertwined with code in difficult-to-manage ways. While it was possible to write clean ASP code, it took a lot of work, and the language and tools were not sufficiently helpful. Even so, ASP did provide full control over the markup produced — it just took a lot of work.

In January 2002, Microsoft released version 1.0 of the .NET platform, which included the original version of ASP.NET. Thus Web Forms was born, and its birth provided access to advanced tools and object-oriented languages for building a website.

ASP.NET has grown tremendously over the last eight years. It has made developing web pages very productive and simple by abstracting the repetitive tasks of web development into simple, drag-and-drop controls. While this abstraction can be a tremendous help, some developers have found that they want more control over the generated HTML and browser scripting, and they also want to be able to test their web page logic easily.

As languages matured and web server software grew in capability, MVC soon found its way into web application architectures. But MVC didn't hit its mainstream stride until July 2004, when a 24-year-old developer at 37Signals in Chicago, Illinois, named David Heinemeier Hansson, introduced the world to his fresh way of thinking about MVC.

David, or DHH as he's known in the community, created Rails, a web development framework that used the Ruby language and the MVC pattern to create something special.

There are a lot of web development frameworks, so perhaps the best way to understand the importance of MVC is to briefly discuss the other options out there in this section. Later in the chapter, we'll further delve into the new kid on the block, MVC, and answer the question, "Why not Web Forms?"

Ruby on Rails

Ruby on Rails (or Rails, as it's colloquially known) is arguably one of the most popular MVC frameworks ever created for the Web. It works according to two major guiding principles:

  • Convention over Configuration: The idea is that as developers we've been doing web development for years now. Let's agree on the things that work and make that part of the framework.

  • Don't Repeat Yourself, or Keep It DRY: This applies to centralizing the logic of an application as well as the code. If you keep this idea in mind, you'll find yourself writing a lot less code.

One of Rails' great strengths lies in its language: Ruby. Ruby is a dynamic language. It supports dynamic and duck typing and it's compiled on the fly by an interpreter. Therefore, you're free to do some interesting language gymnastics. The expressiveness and readability of Ruby are its trademarks; many developers literally have "love at first site" when reading a Ruby tutorial. Ruby, and consequently Rails, have developed their own aesthetic, and Rails programmers value that sense of beautiful code. Rails is often called opinionated software, and it prides itself on its terse but powerful idiomatic framework. There is a thriving community of third-party open source plug-ins to Rails.

Rails also includes the concept of routing, mapping URLs to controllers via the config/routes.rb file. For example, this Rails command:

map.connect ':controller/:action/:id'

would route any URL with this general format to the appropriate controller action method, and pass along the ID as an argument. So, www.example.com/products/category/13 is routed to the ProductsController's Category action passing in an id parameter of 13. You'll learn about routing and ASP.NET MVC in Chapter 4.

Rails is primarily a LAMP (Linux/Apache/MySQL/PHP) platform, but efforts are being made as of the time of writing to offer better support for it using Microsoft's IIS 6 and IIS 7 with FastCGI. Also, John Lam and the Dynamic Languages team at Microsoft demonstrated IronRuby — a .NET language running via the .NET Dynamic Language Runtime (DLR) — with an unmodified version of Rails at RailsConf in Portland, Oregon, in early 2008. IronRuby 1.0 RC3 was released in March, 2010, indicating that a final 1.0 release is close at hand.

Django and Python

Django calls itself "the web framework for perfectionists with deadlines." It is a web framework that uses the Python language and values clean design. Django focuses on automating as much as possible and also values the DRY principle.

Django includes an object-relational mapper that allows you to describe a database using Python code. Like Rails, it also includes the ability to automatically generate an administrative interface, often called scaffolding. It includes a pluggable templating system, which allows for template reuse via inheritance to avoid redundancy whenever possible. Django also has the ability to integrate with a very powerful caching framework called memcached that's also often used in Rails applications.

You'll find the concept of routing in nearly all major MVC web frameworks, and Django is no exception. In Django, routes are declared in a file called urls.py. Django uses Regular Expressions to map between URLs and methods. For example, the following code snippet:

(r'^(?P<object_id>d+)/products/category/$', ' 'store.products.view'),

would route any URL in format www.example.com/products/category/13 to the Django function called store.products.view, passing in an argument id with the value 13. This is just a very simple example, as this isn't a book on Django, but it's important to know and remember that the concepts that you'll find in ASP.NET MVC are concepts that are shared by nearly every major web framework that adheres to the Model-View-Controller pattern.

Spring, Struts, and Java

In the Java space alone, there are three major MVC players: Apache Struts, the Spring Framework, and JSF, which is the J2EE standard MVC framework. There have been others, but these are the top three, and some would argue that JSF is a distant third at that.

  • Spring: This is a Java/J2EE framework, started in 2003, that values object-oriented design, interfaces over classes, and testability over all other considerations. It's more than just an MVC framework — it's a business objects framework, and even if its MVC aspects are not used, you'll find Spring inside, at least the business tier, of almost every recent Java application. Spring includes a component container and transaction support integration with several object-relatIonal mappers. It's focused on making your Java applications as simple and flexible as possible using POJOs (Plain Old Java Objects) and eschewing aspects of Java/J2EE that it considers bloated. Spring includes an MVC Framework that provides an application context for web applications that can enable Spring to work with other Java web frameworks, such as Struts. It supports pluggable views and is generally considered lighter weight than Struts. Spring is easy to test and is almost too flexible in the choices it gives you.

  • Struts: This was released in June 2001, and later the WebWorks and Struts communities merged and created Struts2. It's often considered the standard framework, and more and more is used in tandem with the Spring Framework.

  • JSF: This is a Java-based MVC development framework that provides a set of standard, reusable GUI components for web development. There are a number of vendor implementations of JSF. JSF provides component-based tags for every kind of input tag available in standard HTML. JSF's component set includes an event publishing model, a lightweight IoC (inversion of control) container. It includes server-side validation, data conversion, and page navigation management.

Regardless of their differences, all these Java frameworks share the concepts of a Model, a View, and a Controller. They differ slightly in their life cycles and the things they each value, but the essential goal is the same — clean separation of concerns.

Zend Framework and PHP

PHP applications are usually not given much respect on the Web, even though much of the Web runs on PHP. Many developers think that PHP encourages spaghetti code, and it's not hard to find entire PHP applications written in a single file called index.php.

The Zend Framework, or ZF, is an open-source web application framework implemented in PHP5 that tries bringing a little formality to PHP application development while still providing the kind of flexibility that PHP developers are used to. The Zend Framework doesn't require developers to use these components, as it promotes a "use-at-will" philosophy.

ZF also implements a front-controller model, using convention over configuration whenever possible. It includes its own view templating engine and also supports plugging in alternative views.

MonoRail

Inspired by Ruby on Rails, the first successful Model-View-Controller framework for ASP.NET is called MonoRail and is part of the larger Castle Project. Castle was founded by Hamilton Verissimo de Oliveira, who started his own company in 2006 to offer commercial support for the Castle Project and applications developed using it. The overarching Castle Project offers several features outside of MonoRail like a lightweight inversion of control container called Windsor and an implementation of the active record pattern using NHibernate. At the time of this writing, Hamilton had recently joined Microsoft as a program manager.

MonoRail was created to address frustrations with Web Forms and is a simplification of the standard Web Forms paradigm. MonoRail embraces a front-controller architecture wherein the entry point into your application is an instance of a Controller. Contrast this with an instance of a Page, which is the standard entry point in an ASP.NET Web Forms application.

MonoRail is a very flexible .NET application framework and allows you to plug-and-play various components. It has many extensibility points, but it is very prescriptive and by default pulls in a number of open source applications like NHibernate for Models, log4net for logging, as well as Castle's own ActiveRecord.

MonoRail is often considered one of the best examples of a well-run .NET open source project because of its inclusiveness and focus on simplicity and best practices. MonoRail is also known for its ability to run on Mono, Novell's open source implementation of the .NET Framework, although it's just coincidence that they share the Mono part of their names.

ASP.NET MVC: THE NEW KID ON THE BLOCK

In February 2007, Scott Guthrie ("ScottGu") of Microsoft sketched out the core of ASP.NET MVC while flying on a plane to a conference on the East Coast of the United States. It was a simple application, containing a few hundred lines of code, but the promise and potential it offered for parts of the Microsoft web developer audience was huge.

As the legend goes, at the Austin ALT.NET conference in October 2007 in Redmond, Washington, ScottGu showed a group of developers "this cool thing I wrote on a plane" and asked if they saw the need and what they thought of it. It was a hit. In fact, many people were involved with the original prototype, codenamed Scalene. Eilon Lipton e-mailed the first prototype to the team in September 2007, and he and ScottGu bounced prototypes, code, and ideas, back and forth via email, and still do!

ASP.NET MVC relies on many of the same core strategies that the other MVC platforms use, plus it offers the benefits of compiled and managed code and exploits new language features of VB9 and C#3 like lambdas and anonymous types. Each of the MVC frameworks discussed above shares in some fundamental tenets:

  • Convention over configuration

  • Don't repeat yourself (aka the DRY principle).

  • Pluggability whenever possible

  • Try to be helpful, but if necessary, get out of the developer's way.

These frameworks also share in some other characteristics, as discussed in the next sections.

Serving Methods, Not Files

Web servers initially served up HTML stored in static files on disk. As dynamic web pages gained prominence, web servers served HTML generated on-the-fly from dynamic scripts that were also located on disk. With MVC, it's a little different. The URL tells the Routing mechanism (which you'll get into in Chapter 4) which Controller to instantiate and which Action method to call, and supplies the required arguments to that method. The Controller's method then decides which View to use, and that View then does the rendering.

Rather than having a direct relationship between the URL and a file living on the web server's hard drive, there is a relationship between the URL and a method on a controller object. ASP.NET MVC implements the front controller variant of the MVC pattern, and the Controller sits in front of everything except the Routing subsystem, as you'll see in Chapter 3.

A good way to conceive of the way that MVC works in a Web scenario is that MVC serves up the results of method calls, not dynamically generated (aka scripted) pages. In fact, I heard a speaker once call this RPC for the Web, which is particularly apt, although quite a bit narrower in scope.

Is This Web Forms 4.0?

One of the major concerns that we've heard when talking to people about ASP.NET MVC is that its release means the death of Web Forms. This just isn't true. ASP.NET MVC is not ASP.NET Web Forms 4.0. It's an alternative to Web Forms, and it's a fully supported part of the framework. While Web Forms continues to march on with new innovations and new developments, ASP.NET MVC will continue as a parallel alternative that's totally supported by Microsoft.

One interesting way to look at this is to refer to the namespaces these technologies live in. If you could point to a namespace and say, "That's where ASP.NET lives," it would be the System.Web namespace. ASP.NET MVC lives in the System.Web.Mvc namespace. It's not System.Mvc, and it's not System.Web2.

While ASP.NET MVC 1.0 shipped as a separately downloadable web component (often referred to by the ASP.NET team as an Out-of-Band release or OOB release), ASP.NET MVC 2 is included with Visual Studio 2010.

Why Not Web Forms?

In ASP.NET Web Forms, you create an instance of System.Web.UI.Page and put Server Controls on it (let's say, a calendar and some buttons) so that the user can enter/view information. You then wire these controls to events on the System.Web.UI.Page to allow for interactivity. This Page is then compiled, and when it's called by the ASP.NET run time, a server-side control tree is created, each control in the tree goes through an event life cycle, it renders itself, and the result is served back as HTML. As a result, a new web aesthetic started to emerge — Web Forms layers eventing and state management on top of HTTP — a truly stateless protocol.

Why was this done? Remember that Web Forms was introduced to a Microsoft development community that was very accustomed to Visual Basic 6. Developers using VB6 would drag buttons onto the design surface and double-click the button, and a Button_Click event handler method was instantly created for them. This was an incredibly powerful way to create business applications and had everyone excited about RAD (Rapid Application Development) tools. When developers started using "Classic" ASP, it was quite a step backward from the rich environment they were used to in Visual Basic. Web Forms brought that Rapid Application Development experience to the Web.

However, as the Web matured and more and more people came to terms with their own understanding of HTML as well as the introduction of CSS (Cascading Style Sheets) and XHTML, a new web aesthetic started to emerge. Web Forms is still incredibly productive and enables a developer to create a Web-based line of business applications very quickly. The HTML it generates, though, looks, well, generated, and can sometimes offend the sensibilities of those who handcraft their XHTML and CSS sites. Web Forms concepts like ViewState and the Postback Event model have their place, but many developers want a lower-level alternative that embraces not only HTML but also HTTP itself.

Additionally, the architecture of Web Forms also makes it difficult to test using the current unit testing tools like NUnit, MbUnit, and xUnit.NET. ASP.NET Web Forms wasn't designed with unit testing in mind, and while there are a number of hacks to be found on the Web, it's fair to say that Web Forms does not lend itself well to Test-Driven Development. ASP.NET MVC, however, offers absolute control over HTML, doesn't deny the existence of HTTP, and was designed from the ground up with an eye toward testability. You'll learn more about how ASP.NET MVC supports testability throughout this book, along with deeper coverage in Chapter 11.

Cost/Benefit of Web Forms

ASP.NET Web Forms offers many benefits, but with these benefits come some costs. Currently, Web Forms values speed of development over absolute control of your HTML. You may wonder why it's so important to understand what Web Forms brings to the table and why we, the authors, are spending any time on it in this book. Well, ASP.NET MVC is a completely different paradigm from Web Forms, and to fully understand one side of a coin, it's helpful to study the other side.

Web Forms was a complete departure from Classic ASP and is still virtually unique on the Web with the following features:

  • Server-Side Controls: With the introduction of controls and the control hierarchy, Web Forms instantiates controls on the server side and gives them a complete life cycle. Controls participate in the larger Page life cycle as well as their own life cycle. They can make decisions about how they're going to render themselves to the client. Some of these decisions are based on state, and that state will automatically be managed for the controls as a user moves from page to page.

  • Event Model: Web Forms very nearly hides the fact that the HTTP protocol is stateless by introducing an event model similar to that seen in VB6 and other user-interface toolkits only seen on the desktop. The goal was to bring web development to a whole new group of programmers who hadn't yet drunk deeply of the Internet and the internals of its protocols. There are no events in HTTP; there is simply the retrieval of a resource via a GET request and the submission of data using a POST. Yes, there are other HTTP verbs, but GET/POST to/from a URL comprises more than 99 percent of the cases on the Internet today. Web Forms gave every HTML control the associated server-side class, but it also gave them events. Suddenly, Buttons had Click events, TextBoxes had TextChanged events, and Dropdowns had SelectedIndexedChanged events. An entire object-oriented model was created to abstract away the fundamentals of HTML and HTTP. You'll see exactly the kinds of problems that the design of Web Forms was trying to solve in Chapter 3 and contrast that with the design goals of ASP.NET MVC.

  • State Management: To support this object model and those objects' events, the underlying Web Forms subsystem has to keep track of the state of the view so that it can fire events letting you know that a TextBox's value has changed or that a ListBox has a new selection. However, this state management comes at a cost, and that cost is the delivery of the state of the view to and from the client within a hidden text field containing the ViewState. ViewState is one of the most maligned aspects of the ASP.NET Framework, but it arguably makes the whole thing work. It can certainly be abused if it's not understood. In fact, a great deal of work has been done on the Web by enterprising developers to try to get all the benefits of Web Forms without incurring any of the cost of ViewState. We will dig into exactly what ViewState accomplishes and how it does it in Chapter 3, and we'll do that just seconds before we tell you that ASP.NET MVC explicitly doesn't use ViewState and why that's a good thing!

Should You Fear ASP.NET MVC?

The very fact that ASP.NET MVC doesn't require server-side controls, doesn't include an event model, and doesn't include explicit state management might make you afraid, or it might make you feel empowered. Depending on where you're coming from, there are actually many reasons you might look a little askance at ASP.NET MVC.

It's the End of Web Forms!

ScottHA's given several talks on ASP.NET MVC at a number of conferences, and one of the questions that he asks the audience is:

Who here is attending this talk because you are concerned that ASP.NET MVC is going to throw out all of your existing knowledge on Web Forms and require you to learn a new technology?

It might seem like a silly question on its face, but inevitably, a non-zero percentage of people raise their hands sheepishly. It's true, new technologies are continuing to be churned out of Microsoft and other companies, and it's difficult to tell which one is the Next Big Thing. In this case, frankly, Microsoft is a little late to the MVC game, and is playing catch-up. But the intent is absolutely not to introduce ASP.NET MVC as a replacement for anything, or as anything more than an alternative. If you value the tenets and principles that the ASP.NET MVC is built on, then you should use it. If you don't, you should happily use ASP.NET Web Forms, secure in the knowledge that it will be around and be supported for a very long time. Remember that Microsoft supports developer products for a minimum of 10 years (5 years of mainstream support and 5 years of extended support) and even now continues to support the VB6 run time, even on Windows Vista and Windows Server 2008. Web Forms isn't going anywhere, so you shouldn't fear ASP.NET MVC out of a concern for Web Forms going away.

It's Totally Different!

Yes, it is totally different. That's the whole point. It's built on top of a system of values and architectural principles that is very different from those in Web Forms. ASP.NET MVC values extensibility, testability, and flexibility. It's very lightweight and doesn't make a lot of assumptions on how you will use it — aside from the fact that it assumes you appreciate the Model-View-Controller pattern.

Different developers and different projects have different needs. If ASP.NET MVC meets your needs, use it. If it doesn't, don't use it. Either way, don't be afraid.

SUMMARY

Even though it's going on 35 years old, the Model-View-Controller pattern still has a lot of life in it. There's renewed enthusiasm around this pattern in nearly every programming language available on the Web today. The MVC pattern values separation of concerns, and good implementations of the pattern value extensibility and flexibility, supporting developer choice. Within the last five years, testability has become even more important as agile methodologies and Test Driven Development (TDD) have become part of our daily lives. While still a 1.0 product, ASP.NET MVC sits on top of, and was developed with, everything that makes System.Web a powerful and stable part of the .NET Framework.

ASP.NET MVC's commitment to extensibility allows it to fit easily into a larger ecosystem that includes software from Microsoft, third-party vendors, and a host of open source options. All of this has made Scott Guthrie, Rob, Phil, Jon, and me (Scott Hanselman) into happier, more empowered developers, and we hope ASP.NET MVC will make you happy, too.

Let's dig in.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset