《Pro ASP.NET MVC Framework》翻译——第一章

    自从ASP.NET MVC发布以来,一直备受关注,博客园中已有不少这方面的好文章,但对初学者来说,系统学习MVC的资料还是有些匮乏,一些国外的书籍相当优秀,但还未来得及出中文版,直接阅读英文版相对大多数人,花费的时间比较多,因此我这里尝试将这本书翻译出来,这大概是目前最新和最完整介绍ASP.NET MVC的书籍,希望能对初学者有所帮助。该书由Apress出版社出版,黑皮书,我想原版书的质量不用我说都能明白,翻译中我会尽我所能,但由于本人才疏学浅,无论英文水平,编程能力,还是文学修养方面都有待于提高,因此翻译之后的质量比起原版一定是大打折扣,也希望大家能多多指出错误和不足。翻译采取中英文对照,英文部分在上,翻译在下,以方便阅读者对照。

 

PART 1 Introducing ASP.NET MVC

ASP .NET MVC is a radical shift for web developers using the Microsoft platform. This new framework emphasizes clean architecture, design patterns, and testability. The first part of this book is designed to help you understand broadly the foundational ideas of ASP.NET MVC and to experience in practice what it’s like to use

第一部分ASP.NET MVC介绍

对于使用微软平台的web开发者而言,ASP.NET MVC是一个根本的转变。这个新的框架强调干净的架构,设计模式和可测试性。本书的第一部分帮助你理解ASP.NET MVC的基础并在实战中展示它用起来是什么样的。

 

CHAPTER 1  What’s the Big Idea?

ASP.NET MVC is a web development framework from Microsoft that combines the effectiveness and tidiness of model-view-controller (MVC) architecture, the most up-to-date ideas and techniques from agile development, and the best parts of the existing ASP.NET platform. It’s a complete alternative to “traditional” ASP.NET WebForms, delivering considerable advantages for all but the most trivial of web development projects.

 

第一章   到底是什么?

ASP.NET MVC是来自于微软的web开发平台,它是模型-视图-控制器(MVC)体系结构下效率与整洁的统一,该体系结构来源于敏捷开发最前沿的想法和技巧,也是现在ASP.NET平台最好的部分。它是“传统”ASP.NET WebForms模型的完全改变,对于所有项目都提供很大优势,尤其对于web开发项目是至关重要的。

 

A Brief History of Web Development

To understand the distinctive aspects and design goals of ASP.NET MVC, it’s worth considering the history of web development so far—brief though it may be. Among Microsoft’s web development platforms, we’ve seen over the years an ongoing increase in power and (unfortunately) complexity. As shown in Table 1-1, each new platform tackled the specific shortcomings of its predecessor.

 

Web开发的简要历史

要理解ASP.NET MVC的区别和设计目的,需要考虑迄今为止web开发的历史——虽然可能很简短。我们可以看到,在过去的数年中,微软的web开发平台在功能和复杂性(这点很不幸)上不断提高。如表1-1所示,每一个平台解决了它前辈的一个特定缺点。

 

Table 1-1.Microsoft’s Lineage of Web Development Technologies

Time Period

Technology

Strengths

Weakness

Jurassic

Common Gateway

Interface (CGI)*

Simple

Flexible

Only option at the time

Runs outside web server, so is resource

intensive (spawns separate OS process per

request)

Low-level

Bronze age

Microsoft Internet

Database Connector

(IDC)

Runs inside web server

Just a wrapper for SQL queries and templates

for formatting result set

1996

Active Server Pages (ASP)

General-purpose

Interpreted at runtime

Encourages “spaghetti code”

2002/03

ASP.NET 1.0/1.1

Compiled

Stateful” UI

Vast infrastructure

Encourages  object-oriented programming

Heavy on bandwidth

Ugly HTML

Untestable

2005

ASP.NET 2.0

2007

ASP.NET AJAX

2008

ASP.NET 3.5

* CGI is a standard means of  connecting a web server to an arbitrary executable program that returns dynamic content. Specification maintained by National Center for Supercomputing Applications (NCSA).

 

1-1.微软web开发技术世系

Time Period

Technology

Strengths

Weakness

侏罗纪

公共网关接口(CGI)*

简单

可扩展

当时唯一的选择

运行在web服务器外部,因此是资源密集的(

每个请求产生一个独立的操作系统进程)

低级

铜器时代

因特网数据库连接器

(IDC)

web 服务器内部运行

只是对sql查询和模版的包装,用于格式化结果集

 

1996

活动服务器页面(ASP)

通用

运行时解释

鼓励“意大利面条式代码”

2002/03

ASP.NET 1.0/1.1

编译的

具有“状态”的用户接口

庞大的架构

鼓励面向对象编程

带宽占用严重

丑陋的HTML标记

难以测试

2005

ASP.NET 2.0

2007

ASP.NET AJAX

2008

ASP.NET 3.5

*CGI是任意一个进程访问web服务器并返回动态内容的标准方法。该规范由美国国家超级计算应用中心(NCSA)维护。

 

In just the same way, ASP.NET MVC is designed to tackle the specific shortcomings of traditional ASP .NET WebForms, but this time by trying to emphasize simplicity.

 

同样,ASP.NET MVC被设计用来解决传统ASP.NET WebForms模型的特定缺点,但是这次重点强调简洁。

 

Traditional ASP.NET

ASP.NET was a huge shift when it first arrived, not just in terms of the brand-new .NET multilanguage managed code platform(which was a landmark in its own right), but in that it sought to close the gap between stateful, object-oriented Windows Forms development and stateless, HTML-oriented web development.

Microsoft attempted to hide both HTTP (with its intrinsic statelessness) and HTML(which, at the time, was unfamiliar to many developers) by modeling a user interface (UI) as a server-side hierarchy of control objects. Each control kept track of its own state across requests(using the ViewState facility), automatically rendered itself as HTML when needed, and automatically connected client-side events (e.g., a button click) with the corresponding server-side event handler code. In effect, WebForms is a giant abstraction layer aimed to deliver a classic event-driven GUI over the Web.

Developers no longer had to work with a series of independent HTTP requests and responses, as we did with earlier technologies; we could now think in terms of a stateful UI. We could “forget” about the Web, build UIs using a drag-and-drop designer, and imagine that everything happened on the server.

 

传统的ASP.NET

ASP.NET刚出现的时候是一个巨大的转变,不仅仅因为它是全新的.NET多语言托管代码平台(该平台本身也是一个里程碑),而是它试图填补具有状态的,面向对象的windows窗体开发和无状态的,面向HTMLweb开发之间的空白。

微软试图通过将用户接口(UI)建模为服务器端具有层次的控件来隐藏HTTP(其固有的无状态性)和HTML(在当时很多开发者并不熟悉)。每个控件在请求期间跟踪自己的状态(通过ViewState),在需要的时候自动呈现为HTML,并且自动连接客户端事件(例如一次按钮的点击)和相应的服务器端事件处理代码。事实上,WebForms是一种巨大的抽象,其目的是将传统的事件驱动的GUI用于web上。

开发者不必再象早期那样为了一系列独立的HTTP请求和响应而编写代码,我们现在只需要按照有状态的UI来考虑。我们可以“忘记”关于web的东西,通过拖拽建立UI,想象所有的事情都发生在服务器上。

 

What’s Wrong with Traditional ASP.NET?

Traditional ASP.NET was a fine idea, and a thrilling prospect at first, but of course reality turned out to be more complicated. Over the years, real-world use of WebForms uncovered a range of weaknesses:

ViewState: The actual mechanism of maintaining state across requests (ViewState) often results in giant blocks of data being transferred between client and server. It can reach hundreds of kilobytes in many real-world applications, and it goes back and forth with every request, frustrating site visitors with a long wait each time they click a button or try to move to the next page on a grid. ASP.NET Ajax suffers this just as badlyIt has to send the entire page’s ViewState data back and forth in each asynchronous request., even though bandwidth-heavy page updating is one of the main problems that Ajax is supposed to solve.

Page life cycle: The mechanism of connecting client-side events with server-side event handler code, part of the page life cycle, can be extraordinarily complicated and delicate. Few developers have success manipulating the control hierarchy at runtime without getting ViewState errors or finding that some event handlers mysteriously fail to execute.

Limited control over HTML: Server controls render themselves as HTML, but not necessarily the HTML you want. Not only does their HTML often fail to comply with web standards or make good use of CSS, but the system of server controls generates unpredictable and complex ID values, which are hard to access using JavaScript.

False sense of separation of concerns: ASP.NET’s code-behind model provides a means to take application code out of its HTML markup and into a separate code-behind class. This has been widely applauded for separating logic and presentation, but in reality, developers are encouraged to mix presentation code (e.g., manipulating the server-side control tree) with their application logic (e.g., manipulating database data) in these same monstrous code-behind classes.Without better separation of concerns, the end result is often fragile and unintelligible.

Untestable:When ASP.NET’s designers first set out their platform, they could not have anticipated that automated testing would become such a mainstream part of software development as it is today. Not surprisingly, the architecture they designed is totally unsuitable for automated testing.

ASP .NET has kept moving. Version 2.0 added a set of standard application components that can significantly reduce the amount of code you need to write yourself. The Ajax release in 2007 was Microsoft’s response to the Web 2.0/Ajax frenzy of the day, supporting rich client-side interactivity while keeping developers’ lives simple(Ironically, Microsoft actually invented XMLHttpRequest, the backbone of Ajax technology, to support Outlook Web Access. However, Microsoft didn’t really capitalize on its potential until hundreds of others already had.). The most recent 3.5 release is a smaller enhancement, adding support for .NET 3.5 features and a set of new controls. The new ASP .NET Dynamic Data facility generates simple database list/edit screens automatically. The forthcoming ASP.NET 4.0, to be shipped with Visual Studio 2010, will give developers the option of explicitly controlling certain HTML element IDs, reducing the problem of unpredictable and complex ID values.

 

ASP.NET有什么问题吗?

起初,ASP.NET是个好主意,并且令人兴奋,但事实上它太复杂了。 在过去的数年中,真实的WebForms程序显出一系列的缺点:

视图状态: 在请求之间维持状态的机制(视图状态)经常导致客户端与服务器之间大量数据的传送。 在真实的程序中,它能够达到数百K字节, 在每次请求之间来回传送, 每次站点的访问者需要点击一个按钮或者表格的下一页,都要经历令人沮丧的长时间等待。 ASP.NET Ajax在这一点上同样糟糕(它需要在每次异步请求中来回传递整个页面的状态., 虽然Ajax的一个主要目的是解决占用大量带宽页面的问题。

页面生命周期:页面生命周期中连接客户端与服务器事件的代码可能相当的复杂和精巧。很少有开发者能够在运行时成功的操纵控件的层次结构而没有视图状态的错误或者发现一些事件处理函数神秘失效。

HTML的有限控制:服务器控件将它们自身呈现为HTML,但可能不是想你想要的。它们产生的HTML不兼容web标准,没有有效利用CSS,并且生成不可预知的,复杂的ID,难以使用JavaScript来访问。

对分离关注的错误理解: ASP.NET的代码隐藏(code-behind)模型提供了一种将应用程序代码 从它的HTML标记中分离到一个单独的代码隐藏类里边。显示和逻辑的分离赢得了广泛的喝彩,但事实上,程序员被鼓励将显示的代码(例如操纵服务器端控件树)和应用程序逻辑(例如操作数据库)混合在同一个畸形的代码隐藏类里边。没有更好的分离关注,使得应用程序脆弱和难以理解。

难以测试:ASP.NET的设计者最初建立这个平台的时候,并没有预测到如今自动化测试会成为软件开发主流的一部分。因此,他们设计的体系结构总体上不适合自动化测试也就一点也不奇怪了。

ASP.NET在不停的前进。2.0增加了一系列标准的应用程序组件,大大减少了需要自己手动编写的代码。2007年发布的Ajax是微软对当时Web 2.0/Ajax的呼唤做出的响应,它在支持富客户端交互的同时,使得程序员象以前那样轻松编写代码(具有讽刺意味的是,虽然微软发明了XMLHttpRequest——这是Ajax技术的主要成分——来支持OutlookWeb的访问,但是直到Ajax被大量应用,微软才认识到它的潜力)。最近发布的3.5版本有一些小的改进,支持.NET 3.5的特性,增加了一系列新的控件。新的ASP.NET动态数据工具自动产生简单的数据库显示与编辑界面。即将到来的ASP.NET 4.0和随之而来的VS 2010,将给开发者提供显式控制HTML元素ID的机会,以减少无法预知的,复杂的ID带来的问题。

 

Web Development Today

Outside Microsoft, web development technology has been progressing rapidly in several different directions since WebForms was first released. Aside from Ajax, which I’ve already noted, there have been a few other major developments.

Web Standards and REST

The drive for web standards compliance hasn’t reduced in recent years; if anything, it’s increased. Web sites are consumed on a greater variety of devices and browsers than ever before, and web standards (for HTML, CSS, JavaScript, etc.) remain our one great hope for getting a decent browsing experience everywhere (even on the Internet-enabled refrigerator). Modern web platforms cannot afford to ignore the business case and the weight of developer enthusiasm for web standards compliance.

At the same time, REST is gaining enormous popularity as an architecture for application interoperability over HTTP—especially in the Web 2.0 world of informal “mash-ups.” The distinction between web services and web applications is eroding now that we have rich Ajax  and Silverlight clients, and REST dominates over SOAP in these scenarios. REST requires an approach to HTTP and URL handling that has not easily been supported by traditional ASP.NET.

Ruby on Rails

In 2004, Ruby on Rails was a quiet, open source contribution from an unknown player. Suddenly it hit fame, transforming the rules of web development. It’s not so much that it contained revolutionary technology, but more that it took existing ingredients and blended them in such a wonderful, magical, delicious way as to put existing platforms to shame.

By applying MVC architecture (an old pattern that many web frameworks have recently rediscovered), by working in tune with the HTTP protocol instead of against it, by promoting conventions instead of the need for configuration, and by integrating an object-relational mapping (ORM) tool into its core, Rails applications more or less fell into place without much expense or effort. It was as if this was how web development should have been all along; as if we’d suddenly realized we’d been fighting our tools all these years, but now the war was over.

Rails shows that web standards compliance and RESTfulness don’t have to be hard. It also shows that agile and test-driven development work best when the framework is designed to support them. The rest of the web development world has been catching up ever since.

 

今天的Web开发

在微软之外,自从WebForms第一次发布一来,web开发技术在几个不同的方向快速发展。除了已经提到的Ajax,还有一些其它的web开发技术。

Web 标准和 REST

对于web标准的兼容要求在过去的几年并没有减少,如果要说有什么的话,那就是这种兼容性要求在增加。和过去相比,Web站点现在被非常多的设备和浏览器访问,Web标准(象HTML, CSS ,JavaScript等等)依然是处处(即使是一个联网的冰箱)获得体面的浏览体验的一个很大的希望。现代的web平台不能忽略商业情形和开发者对于web标准兼容性的要求。

与此同时,REST作为一个通过HTTP进行应用程序互操作的架构收到热烈的欢迎,尤其是在Web 2.0时代非正式的“混搭”。现在我们拥有AjaxSilverlight富客户端,使得web服务和web程序的差别正在消失,在这些场景下,RESTSOAP更具优势。REST需要一个HTTPURL处理的入口,这是传统的ASP.NET很难支持的。

Ruby on Rails

2004, Ruby on Rails 是一个不知名的参与者贡献的默默无闻的开源网络应用架构。 它突然出名,改变了web开发的规则。它并没有包含多少革命性的技术,而是更多的采用现有的技术,以一种有趣,魔幻,宜人的方式混合在一起,使得现有的平台相形见绌。

通过应用MVC架构(这是一个被很多web框架最近重新发现的古老模式),通过使用HTTP协议的特点而不是反对它,通过使用约定而不是配置,通过整合对象-关系映射在其核心之中,Rails应用程序或多或少在它合适的位置上,并没有多少花费和努力。好像是web开发一直以来就应该是那样子,好像我们突然意识到这么多年来,我们一直在和我们的工具做斗争,而现在战争结束了。

Rails表明web标准的兼容和REST并不困难,它也表明框架支持敏捷和测试驱动的开发能工作得最好,其它的web开发技术从那时起都跟随上来了。

 

Key Benefits of ASP.NET MVC

A huge corporation like Microsoft can afford to rest on its laurels for a while, but not forever. ASP .NET has been a great commercial success so far, but as discussed, the rest of the web development world has moved on, and even though Microsoft has kept dusting the cobwebs off WebForms, its essential design has started to look quite antiquated.

In October 2007, at the very first ALT.NET conference in Austin, Texas, Microsoft vice president Scott Guthrie announced and demonstrated a brand-new MVC web development platform, built on ASP.NET, clearly designed as a direct response to the criticisms laid out previously. Here’s how it overcomes ASP.NET’s limitations and brings Microsoft’s platform back to the cutting edge.

 

ASP.NET MVC的关键好处

一个象微软这么大的公司,可以因为它的殊荣而停止一段时间,但不能永远。迄今为止,ASP.NET获得了商业上的巨大成功,但是,正如讨论过的,其它的web开发技术已经在前进,即使是微软在不断的清除WebForms的杂乱无章,它的基本的设计已经看起来相当陈旧了。

200710月,在德克萨斯州的奥斯汀的第一次ALT.NET会议上,微软的副总裁Scott Guthrie 宣布并且展示了全新的基于ASP.NETMVC web开发平台,它很明显的被设计为用来回应前边提到的种种批评。下边是它如何克服ASP.NET的限制并且把微软的平台带回到前沿。

 

Model-View-Controller Architecture

ASP .NET MVC provides greatly improved separation of concerns thanks to its adoption of MVC architecture. The MVC pattern isn’t new—it dates back to 1978 and the Smalltalk project at Xerox PARC—but it’s gaining enormous popularity today as an architecture for web applications, perhaps because of the following:

User interaction with an MVC application naturally follows a cycle: the user takes an action, and then in response the application changes its data model and delivers an updated view to the user. And then the cycle repeats. This is a very convenient fit for web applications delivered as a series of HTTP requests and responses.

Web applications already necessitate combining several technologies (e.g., databases, HTML, and executable code), usually split into a set of tiers or layers, and the patterns that arise naturally map onto the concepts in MVC.

ASP .NET MVC implements a modern variant on MVC that’s especially suitable for web applications. You’ll learn more about the theory and practice of this architecture in Chapter 3.

Through this design, ASP.NET MVC directly answers the competition of Ruby on Rails and similar platforms, making a serious effort to bring this style of development into the mainstream of the .NET world, capitalizing on the experience and best practices discovered by developers using other platforms, and in many ways pushing forward beyond what even Rails can offer.

 

模型-视图-控制器架构

由于采用了MVC架构,ASP.NET MVC在关注分离上有了很大的提高。MVC模式并不新颖,它可以追溯到1978年,Xerox PARC Smalltalk项目上,但是它在今天作为web应用程序的架构获得巨大的流行,可能是因为下边的原因:

  MVC应用程序的用户交互自然的遵从一个周期:用户有一个动作,然后作为响应,应用程序改变它的数据模型并且传送一个视图给用户,然后重复该周期。这非常适合传送一系列HTTP请求和响应的web应用程序。

Web应用程序需要组合几种技术(例如数据库,HTML和可执行代码),通常会被分为一系列的层级,在MVC中这些模式是很自然的概念。

ASP.NET MVCMVC的一个现代变体,尤其适合web应用程序。第三章将对该架构的理论和实践做更多的介绍。

通观整个设计,ASP.NET MVC直接回答了和Ruby on Rails及其它平台的竞争问题,努力将这种类型的开发理念融入到.NET世界的主流之中,利用其它开发者在别的平台上的经验和最佳实践,在很多方面甚至已经超越了Rails

 

Extensibility

Your desktop PC’s internal components are independent pieces that interact only across standard, publicly documented interfaces, so you can easily take out your graphics card or hard disk and replace it with another one from a different manufacturer, confident that it will slot in and work. In just the same way, the MVC Framework is built as a series of independent components—satisfying a .NET interface or built on an abstract base class—so you can easily replace the routing system, the view engine, the controller factory, or any other framework component, with a different one of your own implementation. In fact, the framework’s designers set out to give you three options for each MVC Framework component:

1. Use the default implementation of the component as it stands (which should be enough for most applications).

2. Derive a subclass of the default implementation to tweak its behavior.

3. Replace the component entirely with a new implementation of the interface or abstract base class.

It’ s like the Provider model from ASP.NET 2.0, but taken much further—right into the heart of the MVC Framework. You’ll learn all about the various components, and how and why you might want to tweak or replace each of them, starting with Chapter 7.

 

可扩展性

你的电脑的内部组件是相互独立的部分,通过标准的,公开说明的接口相互作用,因此你可以很容易的去掉你的显卡或者硬盘,换上另一个厂家的,你会很自信的认为能够插进去并且能够使用。同样,MVC框架也是由一系列的组件构成,这些组件符合.NET接口或者基于抽象的基类,因此你可以很容易的用自己的不同实现来替换路由系统,控制器工厂,视图引擎,或者其它框架组件。事实上,框架的设计者对于每个MVC组件给你预备了三种选择:

 1. 使用组件的默认实现(对于大多数应用程序应该足够了)。

2. 从一个默认实现的基类继承,用子类来调整行为。

3.实现组件的接口或者从抽象的基类继承,用新的组件完全替代旧的。

这有点象ASP.NET 2.0的提供程序模型,但是更进了一步,直接到了MVC框架的核心。你将从第7章开始学习所有不同组件,如何改变或者替换组件以及为什么要这么做。

 

Testability

MVC architecture gives you a great start in making your application maintainable and testable, because you will naturally separate different application concerns into different, independent software pieces.

Yet the ASP.NET MVC designers didn’t stop there. They took the framework’s component-oriented design and made sure each separate piece is ideally structured for automated testing. So, you can write clean, simple unit tests for each controller and action in your application, using fake or mock implementations of framework components to simulate any scenario. The framework’ s design works around the limitations of today’s testing and mocking tools, and adds Visual Studio wizards to create starter test projects on your behalf (integrating with open source unit test tools such as NUnit and MBUnit as well as Microsoft’s MSTest), so even if you’ve never written a unit test before, you’ll be off to a great start. Welcome to the world of maintainable code!

Throughout this book, you’ll see examples of how to write automated tests using a variety of testing and mocking strategies.

 

易测性

MVC架构给了你一个很好的开始,让你的应用程序易于维护和测试,因为你会自然的将应用程序不同的关注部分分离到不同的,互相独立的软件模块中。.

但是ASP.NET MVC的设计者并没有停留于此,他们采用了面向模块的设计并且确保每一个分离的模块被很好的组织以便于自动化测试。因此你可以为你的应用程序的控制器和动作写出干净,简洁的单元测试,使用假造的或者模拟的框架组件来模拟任何场景。框架的设计在当前的测试和模拟工具的限制之内工作,并且增加了Visual Studio的向导按照你方便的方法来创建最初的测试工程(整合开源的单元测试工具例如NNuitMBUnit,还有微软的MSTest),因此,即使你之前从未写过单元测试,你已经有了一个良好的开始。欢迎来到可维护代码的世界!

你将在本书的例子中看到如何写出不同的测试和模拟策略。

 

Tight Control over HTML

The MVC Framework recognizes the importance of producing clean, standards-compliant markup. Its built-in HTML helper methods do of course produce XHTML-compliant output, but there’s a bigger change of mindset at work. Instead of spewing out huge swathes of barely readable HTML code to represent what should be simple UI elements like lists, tables, or string literals, the MVC Framework encourages you to craft simple, elegant markup styled with CSS. (Plus, Visual Studio 2008’s massively improved CSS refactoring support finally makes it possible to keep track of and sensibly reuse your CSS rules no matter how big your project gets.)

Of course, if you do want to throw in some ready-made widgets for complex UI elements like date pickers or cascading menus, ASP.NET MVC’s “no special requirements” approach to markup makes it dead easy to use best-of-breed open source UI libraries such as jQuery or the Yahoo UI Library. Chapter 12 of this book demonstrates many of these techniques in action, producing rich, cross-browser interactivity with a minimum of fuss. JavaScript developers will be thrilled to learn that ASP.NET MVC meshes so well with the popular jQuery library that Microsoft ships jQuery as a built-in part of the default ASP.NET MVC project template.

ASP.NET MVC–generated pages don’t contain any ViewState data, so they can be hundreds of kilobytes smaller than typical pages from ASP.NET WebForms. Despite today’s fast broadband connections, this bandwidth saving still gives an enormously improved end user experience.

 

HTML的紧密控制

MVC框架认识到生成干净的,和标准兼容的标记的重要性,它内置的HTML辅助方法当然会生成兼容XHTML标准的输出,但是有一个更大的思想倾向的变化在起作用。MVC框架鼓励你使用简单,优雅的带有CSS样式的标记,而不是生成一大堆难以阅读的HTML代码来表示象列表,表格或者字符串这样应该很简单的的UI元素(另外,VS2008大幅提升功能的CSS重构器使得跟踪或者重用你的CSS规则变得很容易,无论你的项目有多大)。

当然,如果你想使用象日期选择器或者层叠式菜单这样已经准备好的复杂UI元素,ASP.NET MVC对于标记“没有特殊需求”的方法使得使用象JQuery或者Yahoo UI库这样非常好的开源UI库非常容易。本书的第12章将在实战中展示很多这方面的技巧,毫不费力的生成富客户端的,跨浏览器的相互作用。Javascript开发者将很兴奋的得知ASP.NET MVC对于流行的JQuery库整合得如此之好以至于微软将JQuery作为内置的ASP.NET MVC默认模版的一部分。

ASP.NET MVC产生的页面不含视图状态数据,因此它们比使用ASP.NET WebForms的典型页面可以小几百K字节,即使是按照现今高速的宽带连接,节省的带宽依然对于终端用户体验有了极大的提升。

 

Powerful New Routing System

Today’s web developers recognize the importance of using clean URLs. It isn’t good for business to use incomprehensible URLs like /App_v2/User/Page.aspx?action=show%20prop&prop_id=82742—it’s far more professional to use /to-rent/chicago/2303-silver-street.

Why does it matter? Firstly, search engines give considerable weight to keywords found in a URL. A search for “rent in chicago” is much more likely to turn up the latter URL. Secondly, many web users are now savvy enough to understand a URL, and appreciate the option of navigating by typing into their browser’s address bar. Thirdly, when someone feels they can understand a URL, they’re more likely to link to it (being confident that it doesn’t expose any of their own personal information) or share it with a friend (perhaps reading it out over the phone). Fourthly, it doesn’t pointlessly expose the technical details, folder, and file name structure of your application with the whole public Internet (so you’re free to change the underlying implementation without breaking all your incoming links).

Clean URLs were hard to implement in earlier frameworks, but ASP.NET MVC uses the brand-new System.Web.Routing facility to give you clean URLs by default. This gives you total control over your URL schema and its mapping to your controllers and actions, with no need to conform to any predefined pattern. Of course, this means you can easily define a modern REST-style URL schema if you’re so inclined.

You’ll find a thorough treatment of routing and URL best practices in Chapter 8.

 

强大的新路由系统

今天的web开发者认识到干净的url的重要性。对商家来说,使用难以理解的象/App_v2/User/Page.aspx?action=show%20prop&prop_id=82742这样的URL并不好,使用/to-rent/chicago/2303-silver-street 则专业的多。

为什么在意这个?首先,搜索引擎会对在URL中找到的关键字的权重给与相当可观的考虑,一个象“rent in Chicago”这样的搜索更容易找到象后者这样的URL。第二,很多web用户现在聪明到足够理解URL,他们会希望给予机会通过在浏览器的地址栏直接键入URL来进行导航。第三,当一些人觉得他们可以理解一个URL,他们更加可能链接它(确信它不会暴露他们的隐私)或者分享给朋友(可能通过电话读出来)。第四,向整个公共因特网暴露你的应用程序的技术细节,文件夹和文件名字的组织结构并不是毫无意义(因此你可以自由的改变底层的实现而不会中断所有进入的链接)。

干净的URL在早先的框架中很难实现,但是ASP.NET MVC使用了全新的System.Web.Routing工具默认让你对URL进行清洁。这给了你对于URL结构的完全控制,可以映射到你的控制器和动作而不需要遵从预先定义的模式。当然,这意味着,只要你愿意,你就可以很容易的定义一个现代的REST类型的URL结构。

你将在第8章对路由和URL的最佳实践进行深入了解。

 

Built on the Best Parts of the ASP.NET Platform

Microsoft’s existing platform provides a mature, well-proven suite of components and facilities that can cut down your workload and increase your freedom. Firstly and most obviously, since ASP .NET MVC is based on the .NET 3.5 platform, you have the flexibility to write code in any .NET language and access the same API features, not just in MVC itself, but in the extensive .NET class library and the vast ecosystem of third-party .NET libraries.

Secondly, ready-made ASP .NET platform features such as master pages, Forms Authentication, membership, roles, profiles, and globalization can significantly reduce the amount of code you need to develop and maintain in any web application, and these are just as effective in an MVC project as in a classic WebForms project. Certain WebForms’ built-in server controls—and your own custom controls from earlier ASP.NET projects—can be reused in an ASP.NET MVC application (as long as they don’t depend on WebForms-specific notions such as ViewState).

Development and deployment are covered, too. Not only is ASP.NET well integrated into Visual Studio, Microsoft’s flagship commercial IDE, it’s the native web programming technology supported by the IIS web server built into Windows XP, Vista, 7, and Server products. IIS 7.0 adds a set of enhanced features for running .NET managed code as part of the request handling pipeline, giving special treatment to ASP.NET applications. Being built on the core ASP.NET platform, MVC applications get an equal share of the benefits.

Chapter 14 explains what you need to know to deploy ASP.NET MVC applications to IIS  on Windows Server 2003 and Server 2008. Chapter 15 demonstrates the core ASP.NET platform features you’re likely to use in an MVC application, showing any differences in usage between MVC and WebForms applications, along with tips and tricks needed to work around compatibility issues. Even if you’re already a seasoned ASP.NET expert, there’s a good chance you’ll find one or two useful components you haven’t yet used.

 

建立在ASP.NET平台最好的一部分上

微软现在的平台提供了一套成熟的,被很好证明了的组件和工具,能够缩减你的费用,增加你的自由。首先而且最明显的是,由于ASP.NET MVC是基于.NET 3.5平台的,你可以用任意一种.NET语言写代码,访问相同的API特征,不单单是MVC本身,而是广泛的.NET类库和大量的第三方.NET类库。

其次,现在的ASP.NET平台的特征例如母版页,Forms身份验证,成员资格管理,角色,用户配置文件(profiles)和全球化能大大减少你在任何web应用程序中的开发或者维护的代码量,并且这些在MVC中和在典型的WebForms工程中同样有效。来自于早期的ASP.NET工程中特定的WebForms的内建服务器控件和你的自定义控件,在ASP.NET MVC应用程序中可以复用(只要它们不依赖WebForms特定的标记例如视图状态)。.

开发和发布也被覆盖到了。不仅ASP.NET被整合到Visual Studio——微软的旗舰商业IDE中,被IIS web服务器支持的编程语言构建在Windows XPVistaWindows 7和服务器产品的。IIS 7.0为了运行作为请求处理管线中的部分.NET托管代码而添加了一系列增强特性,对于ASP.NET应用程序给予特殊的对待。MVC应用程序建立在核心ASP.NET平台上,同样享有这些好处。

14章介绍为了把ASP.NET MVC应用程序部署到Windows Server 2003Windows Server 2008IIS上而需要知道的一些东西。第15章演示了你可能在MVC应用程序中用到的核心ASP.NET 平台特性,指出MVCWebForms应用程序之间用法的差异和处理兼容性问题的技巧。即使你是一个经验丰富的ASP.NET专家,你仍然能够发现一些以前从未用过的有用组件。

 

.NET 3.5 Language Innovations

Since its inception in 2002, Microsoft’s .NET platform has evolved relentlessly, supporting and even defining the state-of-the-art aspects of modern programming. The most significant recent innovation is Language Integrated Query (LINQ), along with bucket loads of ancillary enhancements in C# such as lambda expressions and anonymous types. ASP.NET MVC is designed with these innovations in mind, so many of its API methods and coding patterns follow a cleaner, more expressive composition than was possible when earlier platforms were invented.

 

.NET 3.5语言创新

微软的.NET平台自从2002开始就在不停的发展,支持甚至定义了现代编程的艺术级层面。最近的巨大创新是语言集成查询(LINQ),还有C#语言大量的辅助提升,例如lambda表达式和匿名类型。ASP.NET MVC在设计的时候就考虑到了这些创新,因此和早期的平台相比,它的许多API方法和代码模式更加干净和易于表达。

 

ASP.NET MVC Is Open Source

Faced with competition from open source alternatives, Microsoft has made a brave new move with ASP .NET MVC. Unlike with any previous Microsoft web development platform, you’re free to download the original source code to ASP.NET MVC, and even modify and compile your own version of it. This is invaluable for those occasions when your debugging trail leads into a system component and you want to step into its code (even reading the original programmers’ comments), and also if you’re building an advanced component and want to see what development possibilities exist, or how the built-in components actually work.

Of course, this ability is also great if you don’t like the way something works, find a bug, or just want to access something that’s otherwise inaccessible, because you can simply change it yourself. However, you’ll need to keep track of your changes and reapply them if you upgrade to a newer version of the framework. Source control is your friend here.

ASP .NET MVC has been licensed under Ms-PL (www.opensource.org/licenses/ms-pl.html), an OSI-Approved open source license, which means you can change the source code, deploy it, and even redistribute your changes publicly as a derivative project. However, at present Microsoft is not accepting patches to the central, official build. Microsoft will only ship code that’s the product of their own development and QA teams.

You can download the framework’s source code from http://tinyurl.com/cs3l3n.

 

ASP.NET MVC是开源的

面对开源替代品的竞争,微软的ASP.NET MVC迈出了勇敢的一步。不同于以前的任何一个web开发平台,你可以自由下载ASP.NET的源代码,甚至可以修改和编译自己的版本。当你调试到系统组件并且想要单步执行进入代码(你甚至可以读到原先程序员的注释)的时候,还有你希望建立一个高级的组件想要看看现在的开发工具或者内置的组件是如何工作的,开源的价值是无法衡量的。

当然,如果你不喜欢框架的某种工作方式,要找到一个bug,或者需要访问一些在其它情况下不能访问的组件或者代码,开源的作用都很重要,因为你可以简单的改变它。但是,你需要跟踪改变以便在你升级到新版本的时候能够重新应用它们。在这种情况下,源代码控制是你的好朋友。

ASP.NET MVC遵从Ms-PL许可(www.opensource.org/licenses/ms-pl.html),这是一种OSI规定的开源许可,这意味着你可以改变源代码,发布它,甚至作为一个派生的项目来公开发行。但是,目前微软并不接受第三方补丁来构建重要的,官方的版本,它只用自己的开发团队和QA团队的产品代码

你可以从http://tinyurl.com/cs3l3n下载框架的源代码。

 

Who Should Use ASP.NET MVC?

As with any new technology, its mere existence isn’t a good reason for adopting it (despite the natural tendencies of software developers). Let’s consider how the MVC platform compares to its most obvious alternatives.

 

谁应当使用MVC?

正如任何一种新技术,只是因为它存在就使用它并不是一个好的理由(虽然软件开发者具有这样的自然倾向)。让我们来考虑下MVC和它最明显的替代者相比是怎么样的。

 

Comparisons with ASP.NET WebForms

You’ve already heard about the weaknesses and limitations in traditional ASP.NET WebForms, and how ASP.NET MVC overcomes many of those problems. That doesn’t mean that WebForms is dead, though: Microsoft is keen to remind everyone that the two platforms go forward side by side, equally supported, and both are subject to active, ongoing development. In many ways, your choice between the two is a matter of development philosophy.

WebForms takes the view that UIs should be stateful, and to that end adds a sophisticated abstraction layer on top of HTTP and HTML, using ViewState and postbacks to create the effect of statefulness. This makes it suitable for drag-and-drop Windows Forms–style development, in which you pull UI widgets onto a canvas and fill in code for their event handlers.

MVC embraces HTTP’s true stateless nature, working with it rather than fighting against it. It requires you to understand how web applications actually work; but given that understanding, it provides a simple, powerful, and modern approach to writing web applications with tidy code that’s easy to test and maintain over time, free of bizarre complications and painful limitations.

There are certainly cases where WebForms is at least as good as, and probably better than, MVC. The obvious example is small, intranet-type applications that are largely about binding grids directly to database tables or stepping users through a wizard. Since you don’t need to worry about the bandwidth issues that come with ViewState, don’t need to be concerned with search engine optimization, and aren’t bothered about testability or long-term maintenance, WebForms’ drag-and-drop development strengths outweigh its weaknesses.  On the other hand, if you’re writing applications for the public Internet, or larger intranet applications (e.g., more than a few person-month’s work), you’ll be aiming for fast download speeds and cross-browser compatibility, built with higher-quality, well-architected code suitable for automated testing, in which case MVC will deliver significant advantages for you.

 

ASP.NET WebForms相比

你已经了解了传统的ASP.NET WebForms的缺点和限制,并且知道ASP.NET MVC是怎么解决这些问题的。但是这并不意味着WebForms的死亡,微软强调这两个平台一起前进,受到同样的支持,两者都积极持续的发展。在很多情况下,在两者之间的选择只是开发哲学上的。.

WebForms认为UI应该是有状态的,出于这个原因在HTTPHTML上增加了复杂的抽象层,使用视图状态和回发(postbacks)来产生具有状态的效果。这使得它非常适合拖拽式的Windows Forms类型的开发,在这种情况下,你可以将UI拖拽到画布上,在它们的事件处理函数中编写代码。

MVC支持HTTP自然的无状态特性,利用这一点工作而不是反对它。它需要你了解web应用程序实际上是怎么工作的,一旦你理解了,它提供简单,强大,现代的方法来编写web应用程序,代码干净,易于测试和维护,没有怪异的代码和痛苦的限制。

在一些特定的情况下,WebFormsMVC工作得一样好,甚至更好。一个明显的例子是编写一个小的,企业内部网类型的应用程序,它的大部分是关于将数据库表中的数据绑定到表格中或者通过向导一步步引导用户。由于你不用担心伴随视图状态带来的带宽问题,不在意搜索引擎的优化,不担心可测试行和长期的维护,WebForms的拖拽式方法的优点超过了它的缺点。另一方面,如果你要编写面向公共因特网的应用程序,或者是大型的企业网应用程序(例如不是几个人工作月余可以完成的),你的目标是很快的下载速度,跨浏览器兼容,代码质量高,架构设计好,易于自动化测试,在这种情况下,MVC将给你带来巨大的好处。

 

Migrating from WebForms to MVC

If you have an ongoing ASP.NET project that you’re considering migrating to MVC, you’ll be pleased to know that the two technologies can coexist in the same application at the same time. This gives you an opportunity to migrate your application piecemeal, especially if it’s already partitioned into layers with your domain model or business logic held separately to the WebForms pages. In some cases, you might even deliberately design an application to be  a hybrid of the two technologies. You’ll be able to see how this works in Chapter 16.

 

WebForms迁移到MVC

如果你有一个正在进行的项目考虑迁移到MVC,你将会很高兴的知道这两种技术可以同时存在于同一个应用程序中。这给了你一个机会可以让你逐步迁移你的应用程序,特别是它已经根据领域模型划分了层次或者将业务逻辑分散到不同的WebForms页面中。在一些情况下,你可能会精心的设计应用程序,混合使用两种技术。你将在第16章明白如何进行迁移。

 

Comparisons with Ruby on Rails

Rails has become a bit of a benchmark against which other web platforms must be compared.In this case, the simple reality is that developers and companies who are in the Microsoft .NET world will find ASP.NET MVC far easier to adopt and to learn, whereas developers and companies that work in Python or Ruby on Linux or Mac OS X will find an easier path into Rails. It’s unlikely that you’d migrate from Rails to ASP.NET MVC or vice versa. There are some real differences in scope between the two technologies, though.

Rails is a completely holistic development platform, meaning that it handles the entire stack, right from database source control (migrations), through ORM, into handling requests with controllers and actions and writing automated tests, all topped off with a “scaffolding” system for rapidly creating data-oriented applications.

ASP.NET MVC, on the other hand, focuses purely on the task of handling web requests  in MVC style with controllers and actions. It does not have a built-in ORM tool, nor a built-in unit testing tool, nor a system for managing database migrations, because the .NET platform already has an enormous range of choices, and you should be able to use any one of them. For example, if you’re looking for an ORM tool, you might use NHibernate, or Microsoft’s LINQ to SQL, or Subsonic, or one of the many other mature solutions. Such is the luxury of the .NET platform, although of course it means that these components can’t be as tightly integrated into ASP.NET MVC as the equivalents are into Rails.

 

Ruby on Rails相比

Rails有点象是和其它web平台进行比较的基准。对于ASP.NET MVC RRuby on Rails相比,一个简单的事实是:在微软的.NET世界中的开发者和公司会发现ASP.NET MVC易于采用和学习,而工作在Linux或者Mac Os X上的Python或者Ruby开发者和公司则会觉得Rails容易。看来不太可能从Rails转移到ASP.NET MVC,反之也一样。可是,这两种技术还是有一些真实的差别。

Rails是一个完整的开发平台,这意味着它处理全部的事务,从通过ORM进行数据库控制(迁移)到通过控制器和动作处理请求和编写自动化测试,所有的一切都在一个为了快速创建面向数据的应用程序的“脚手架”系统中完成。

另一方面,ASP.NET MVC只是专注于处理带有控制器和动作的MVC风格的web请求,它没有内置的ORM工具和单元测试工具,没有管理数据库迁移的系统,因为.NET平台在这些方面已经有了很大范围的选择,你应该从中挑选一个。例如,如果你在寻找一个ORM工具,你可以使用NHibernate或者微软的LINQ to SQL,或者Subsonic,或者任何一个成熟的解决方案。这是.NET带来的盛宴,但是理所当然的,这意味着这些组件不能紧密的整合在ASP.NET MVC中,而在Rails中则可以。

 

Comparisons with MonoRail

Up until now, the leading .NET MVC web development platform had been Castle MonoRail, which is part of the open source Castle project in development since 2003. If you know MonoRail, you’ll find ASP.NET MVC uncannily familiar: they’re both based on the core ASP .NET platform and they’re both heavily inspired by Ruby on Rails. They use the same terminology in various places (MonoRail’s founder has been involved in Microsoft’s design process for ASP.NET MVC), and tend to attract the same kind of developers. There are differences, though:

MonoRail can run on ASP .NET 2.0, whereas ASP.NET MVC requires version 3.5.

Unlike ASP.NET MVC, MonoRail gives special treatment to one particular ORM. If you use Castle ActiveRecord (which is based on NHibernate), MonoRail can generate basic data browsing and data entry code automatically.

MonoRail is even more similar to Ruby on Rails. As well as using Rails-like terminology  in places (flash, rescues, layouts, etc.), it has a more rigid sense of design by convention. MonoRail applications tend to use the same, standard URL schema (/controller/action).

MonoRail doesn’t have a direct equivalent to ASP.NET MVC’s routing system. The only way to accept nonstandard inbound URL patterns is to use a URL rewriting system,  and if you do that, there isn’t a tidy way to generate outbound URLs. (It’s likely that MonoRail users will find a way to use the new System.Web.Routing to share the benefits.)

Both platforms have their pros and cons, but ASP.NET MVC has one giant advantage that guarantees it will enjoy far wider acceptance: the Microsoft badge. Whether you like it or not, this really matters in many practical scenarios of trying to convince a client or boss to accept a new technology. Plus, when the elephant moves, swarms of flies follow: thousands of developers, bloggers, and third-party component vendors (and authors!) are scrambling to claim the best places in the new ASP .NET MVC world, making support, tools, and staff far easier to find than—sadly—could ever be possible for MonoRail.

 

MonoRail相比

直到今天,主要的.NET MVC web开发平台还是Castle MonoRail,它是2003年的开源Castle项目的一部分。如果你知道MonoRail,你会发现ASP.NET MVC和它惊奇的相似:它们都建立在ASP.NET平台的核心上,都深受Ruby on Rails的影响。它们在不同的地方使用了相同的技术(MonoRail的创始人参与了微软ASP.NET MVC的设计过程),并且容易吸引同类的开发者。但是,它们也有一些区别:

MonoRail 可以运行在ASP.NET 2.0上,而ASP.NET MVC需要ASP.NET 3.5

不同于ASP.NET MVCMonoRail 使用了一个特定的ORM工具。如果你使用了Castle ActiveRecord(基于NHibernate),MonoRail可以自动产生基本的数据浏览和数据入口代码。

MonoRails更象Ruby on Rails,在一些地方同样使用Rails风格的术语(动画,维护,层次等等),它在约定方面更加刚性。MonoRail应用程序容易使用相同,标准的URL结构(/控制器/动作)。

MonoRail没有直接对应于ASP.NET MVC路由系统的对等物。接受非标准的入站URL唯一的方式是使用URL重写系统,如果你这样做了,没有一个整洁的方式来产生出站URL。(看起来MonoRail用户将找到一种方式来使用新的System.Web.Routing来获得这样的好处)

两种平台各有千秋,但是ASP.NET MVC有一个巨大的优势保证它能被更广泛的接受:因为它是微软的。无论你是否喜欢,事实是,在很多情况下这是试图让客户和老板能够接受一个新技术的理由。另外,当微软这头大象前进时,众多的追随者会跟着一起:成千上万的开发者,博客作者,第三方组件供应商(和作者)纷纷声称进入ASP.NET MVC的世界中,提供支持,工具和管理人员,这些情况比在MonoRail中更容易被发现。

 

Summary

In this chapter, you’ve seen how web development has evolved at tremendous speed from the primordial swamp of CGI executables to the latest high-performance, agile-compliant platforms. You reviewed the strengths, weaknesses, and limitations of ASP.NET WebForms, Microsoft’s main web platform since 2002, and the changes in the wider web development Industry that forced Microsoft to respond with something new.

You’ve seen how this new ASP.NET MVC platform directly addresses the criticisms leveled at ASP.NET WebForms, and how its modern design delivers enormous advantages to developers who are willing to understand HTTP, and who want to write high-quality, maintainable code. You’ve also seen how this platform leads to faster-performing applications that work better on a wider range of devices.

In the next chapter, you’ll see the code in action, learning the simple mechanisms that yield all these benefits. By Chapter 4, you’ll be ready for a realistic e-commerce application built with a clean architecture, proper separation of concerns, automated tests, and beautifully minimal markup.

 

摘要

在本章中,你看到web开发技术以极快的速度从原始的CGI可执行程序到最近的高性能,符合敏捷开发的平台。你回顾了ASP.NET WebForms的长处,弱点和限制,它是自从2002年开始微软的主要web平台,广阔的web开发平台产业的改变使得微软用一些新的东西来做出响应。

你已经看到新的ASP.NET MVC平台直接解决了对ASP.NET WebForms的批评,它的现代设计带给愿意了解HTTP,希望写出高质量可维护代码的开发者巨大的好处。你也看到了这个平台如何导致快速,高性能的应用程序,这些应用程序在更广阔的设备范围内工作得更好。

在下一章,你将看到实际的代码,学习产生这些优点的简单机制。在第4章,你将看到一个真实的电子商务程序,架构干净,正确的分离不同的关注,可以进行自动化测试,具有漂亮的,最少的标记。

 

 

    本人在翻译过程中得到网友水木的大力支持 ,在此表示感谢。

 

 

posted on 2009-10-25 23:44  大笨  阅读(5317)  评论(33编辑  收藏  举报

导航