Yan-Feng

记录经历、收藏经典、分享经验

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Overview
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 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's 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?

Add a note hereModel-View-Controller (MVC) is an architectural pattern used to separate an application into three main aspects:

  • Add a note hereThe 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

  • Add a note hereThe View: The application's user interface (UI)

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

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

  • Add a note hereThe 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.

  • Add a note hereThe 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.

  • Add a note hereFinally, the Controller is a special class that manages the relationship between the View and Model. It 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".

Add a note hereYou'll dive more into where each of these classes lives and why further along in this book.

MVC on the Web Today

Add a note hereFor 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.

Add a note hereAs 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.

Add a note hereASP 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.

Add a note hereIn January of 2002, Microsoft released version 1.0 of the .NET platform, which included the original version of ASP.NET, and thus Web Forms was born, and its birth provided access to advanced tools and object-oriented languages for building a web site.

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

Add a note hereAs 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 of 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.

Add a note hereDavid, 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.

Add a note hereThere 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?"

Add a note hereRuby on Rails

Add a note hereRuby on Rails (or "Rails" as its colloquially known) is arguably one of the most popular MVC frameworks ever created for the Web. It works according to two major guiding principles:

  • Add a note hereConvention 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.

  • Add a note hereDon'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.

Add a note hereOne of Rails' great strengths lies in its language: Ruby. Ruby is a dynamic language. It's not strongly typed, 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, has 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.

Add a note hereRails also includes the concept of routing and map URLs to controllers via the config/routes.rb. For example, this Rails command:

Add a note heremap.connect ':controller/:action/:id'

Add a note herewould route any URL with this general format to the appropriate controller class, 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.

Add a note hereRails 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.

Add a note hereDjango and Python

Add a note hereDjango 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.

Add a note hereDjango 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.

Add a note hereYou'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:

Add a note here(r'^(?P<object_id>\d+)/products/category/$', ‘store.products.view'),

Add a note herewould route any URL in format www.example.com/products/detail/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.

Add a note hereSpring, Struts, and Java

Add a note hereIn 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.

  • Add a note hereSpring 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 a number of 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 and 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.

  • Add a note hereStruts 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.

  • Add a note hereJSF 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 container. It includes server-side validation, data conversion, and page navigation management.

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

Add a note hereZend Framework and PHP

Add a note herePHP 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.

Add a note hereThe 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.

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

Add a note hereMonoRail

Add a note hereInspired 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 a number of 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.

Add a note hereMonoRail was created to address frustrations with Web Forms and is a simplification of the standard Web Forms paradigm." MonoRail embraces a front-controller architecture where 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.

Add a note hereMonoRail 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.

Add a note hereMonoRail 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

Add a note hereIn February of 2007, Scott Guthrie 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.

Important 

Add a note hereProduct Team Aside

Add a note hereScottGu, or "The Gu," is legendary for prototyping cool stuff, and if he sees you in the hallway and he's got his laptop, you'll not be able to escape as he says, "Dude! Check this out!" His enthusiasm is infectious

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

Add a note hereASP.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 share in some fundamental tenets:

  • Add a note hereConvention over configuration

  • Add a note hereDon't repeat yourself (aka the DRY principle)

  • Add a note herePluggability whenever possible

  • Add a note hereTry to be helpful, but if necessary, get out of the developer's way

Add a note hereThese frameworks also share in some other characteristics, as discussed in the next sections.

Add a note hereServing Methods, Not Files

Add a note hereWeb 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.

Add a note hereRather 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.

Add a note hereA 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.

Add a note hereIs This Web Forms 4.0?

Add a note hereOne 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.

Add a note hereOne 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.

Add a note hereWhile ASP.NET MVC is a separately downloadable web component today (often referred to by the ASP.NET team as an Out-of-Band release or "OOB" release), it will be folded into a future version of the .NET Framework and cement its place as a fundamental part of the base class libraries.

Add a note hereWhy Not Web Forms?

Add a note hereIn 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 runtime, a server-side control tree is created, each control in the tree goes through an event lifecycle, 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.

Add a note hereWhy 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. For better or worse, Web Forms brought that Rapid Application Development experience to the Web.

Add a note hereHowever, 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 developers 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.

Add a note hereAdditionally, 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 offers absolute control over HTML, doesn't deny the existence of HTTP, and was designed from the ground up with an eye towards testability. You'll learn more about how ASP.NET MVC supports testability throughout this book, along with deeper coverage in Chapter 11.

Add a note hereCost/Benefit of Web Forms

Add a note hereASP.NET Web Forms offers a lot of 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 the authors are spending any time on this and 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.

Add a note hereWeb forms was a complete departure from Classic ASP and is still virtually unique on the Web with the features:

  • Add a note hereServer-side controls: With the introduction of controls and the control hierarchy, Web Forms instantiates controls on the server side and gives them a complete lifecycle. Controls participate in the larger page lifecycle as well as their own lifecycle. 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.

  • Add a note hereEvent Model: Web Forms very nearly hide 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 over 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.

  • Add a note hereState 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 could fire events letting you know that a TextBox‘s value had changed or that a ListBox had 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 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. The authors 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!

Add a note hereShould You Fear ASP.NET MVC?

Add a note hereThe 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 a number of reasons you might look a little askance at ASP.NET MVC.

It's the End of Web Forms!

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

Add a note here"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?"

Add a note hereIt might seem like a silly question on its face, but inevitably a nonzero 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 is anything more than alternative. If you value the tenets and principles 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 supported for a very long time. Remember that Microsoft supports developer products for a minimum of 10 years (five years of mainstream support and five years of extended support) and even now continues to support the VB6 runtime, 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!

Add a note hereYes, 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.

Add a note hereDifferent 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

Add a note hereEven 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.

Add a note hereASP.NET MVC's commitment to extensibility allows it to easily fit 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, and me (Scott Hanselman) into happier, more empowered developers, and we hope ASP.NET MVC will make you happy, too.

Add a note hereLet's dig in.

posted on 2010-06-23 16:09  Yan-Feng  阅读(377)  评论(0编辑  收藏  举报