【译著】第1章 伟大的思想 — 《精通ASP.NET MVC 3框架》

C H A P T E R 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 Web Forms, delivering considerable advantages for all but the most trivial of web development projects. In this chapter, you’ll learn why Microsoft originally created ASP.NET MVC, how it compares to its predecessors and alternatives, and, finally, what’s new in ASP.NET MVC 3.
ASP.NET MVC是微软的一个web开发框架,它整合了“模型-视图-控制器(MVC)”体系结构的效率与简洁、敏捷开发最现代的思想与技术、以及当前ASP.NET平台最好的部分。它是传统的ASP.NET Web表单的一种完善的替代品,即使是对最微不足道的web项目,它都具备了相当的优势。在本章中,你将了解微软当初为什么要创建ASP.NET MVC,与它的前辈和替代品比较如何,最后介绍ASP.NET MVC 3的新特性。

A Brief History of Web Development
Web开发简史

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. Over the years, Microsoft’s web development platforms have demonstrated increasing power—and (unfortunately) increasing complexity. As shown in Table 1–1, each new platform tackled the specific shortcomings of its predecessor.
要理解ASP.NET MVC的特色及其设计目标,有必要考察一下web开发的历史 — 虽然这很简短。过去几年,微软的web开发平台演变得越加强大 — 也(不幸的是)越加复杂。如表1-1所示,每一个新的平台都修正了它前任的特定弱点。

Table 1–1. Microsoft’s Lineage of Web Development Technologies
表1-1. 微软的Web开发技术谱系
Period
时期
Technology
技术
Strengths
长处
Weaknesses
弱点
Jurassic
侏罗纪
Common Gateway Interface (CGI)*
通用网关接口(CGI)
Simple
Flexible
Only option at the time
简单
灵活
当时的唯一选择
Runs outside the web server, so is resource intensive (spawns a separate OS process per request)
Low-level
运行在web服务器之外,因此是资源密集型的(每个请求产生一个独立的OS进程)
低级
Bronze age
铜器时代
Microsoft Internet Database Connector (IDC)
微软因特网数据库连接器(IDC)
Runs inside web server
在web服务器内部运行
Just a wrapper for SQL queries and templates for formatting result sets
只是SQL查询的一种封装,和对结果集进行格式化的模板
1996 Active Server Pages (ASP)
活动服务器页面(ASP)
General-purpose
通用
Interpreted at runtime
Encourages “spaghetti code”
在运行时解释
鼓励“意大利细面条式代码”
2002/03 ASP.NET Web Forms 1.0/1.1 Compiled “Stateful” UI
Vast infrastructure
Encourages object-oriented programming
编译的“有态”UI
巨大的基础结构
鼓励面向对象编程
Heavy on bandwidth
Ugly HTML
Untestable
沉重的网络带宽
丑陋的HTML
不可测试
2005 ASP.NET Web Forms 2.0
2007 ASP.NET AJAX
2008 ASP.NET Web Forms 3.5
2009 ASP.NET MVC 1.0
2010 ASP.NET MVC 2.0
ASP.NET Web Forms 4.0
Discussed shortly
马上讨论
2011 ASP.NET MVC 3.0

* CGI is a standard means of connecting a web server to an arbitrary executable program that returns dynamic content. The specification is maintained by the National Center for Supercomputing Applications (NCSA).
CGI是把web服务器连接到返回动态内容的任意可执行程序的一种标准方法。其规范由国家超级计算应用中心(NCSA)维护。

Traditional ASP.NET Web Forms
传统的ASP.NET Web表单

ASP.NET was a huge shift when it first arrived in 2002. Figure 1-1 illustrates Microsoft’s technology stack as it appeared then.
ASP.NET在它2002年刚问世时是一个巨大的转变。图1-1描述了它出现时微软的技术堆栈。

图3-1
图3-1c

Figure 1-1. The ASP.NET Web Forms technology stack
图1-1. ASP.NET Web表单的技术堆栈

With Web Forms, Microsoft attempted to hide both HTTP (with its intrinsic statelessness) and HTML (which at the time was unfamiliar to many developers) by modeling the user interface (UI) as a hierarchy of server-side control objects. Each control kept track of its own state across requests (using the View State facility), rendering itself as HTML when needed and automatically connecting client-side events (e.g., a button click) with the corresponding server-side event handler code. In effect, Web Forms is a giant abstraction layer designed to deliver a classic event-driven GUI over the Web.
利用Web表单,微软试图通过把用户界面(UI)模拟为服务器端控件对象层的办法,把HTTP(具有无状态本质)和HTML(当时许多开发人员尚不熟悉)都隐藏起来。每个控件都跨请求地跟踪自己的状态(利用视图状态功能)、在需要时把自己渲染成HTML、并自动地把客户端事件(如按钮点击)与相应的服务器端的事件处理代码相关联。结果,Web表单变成了一个巨大的抽象层,它被设计在Web上递送传统的事件驱动GUI式(图形用户界面)了。

The idea was to make web development feel just the same as Windows Forms development. Developers no longer had to work with a series of independent HTTP requests and responses—we could now think in terms of a stateful UI. We could forget about the Web and its stateless nature and instead build UIs using a drag-and-drop designer and imagine, or at least pretend, that everything was happening on the server.
其思想是,让web开发在感觉上与Windows窗口开发相同。开发者不再必须以一系列独立的HTTP请求和响应进行工作 — 现在可以把它说成是有状态的UI。我们可以忘记Web及其无状态本质,转而用一个拖-放设计器来建立各种UI,并假想,或至少假装,所有事情都发生在服务器上。

What’s Wrong with ASP.NET Web Forms?
ASP.NET Web表单有什么问题?

Traditional ASP.NET Web Forms was a great idea, but reality proved more complicated. Over time, the use of Web Forms in real-world projects highlighted some shortcomings:
传统的ASP.NET Web表单是一种伟大的思想,但事实上却更加复杂。随着时间的推移,在实际项目中使用Web表单突出地表现出了一些缺陷:

  • View State weight: The actual mechanism for maintaining state across requests (known as View State) results in large blocks of data being transferred between the client and server. This data can reach hundreds of kilobytes in even modest web applications, and it goes back and forth with every request, frustrating site visitors with slower response times and increasing the bandwidth demands of the server.
    视图状态负荷:跨请求状态维护的实际机制(称为视图状态)导致在客户端与服务器之间传递大块数据。这种数据即使在最适度的web应用程序中也达到几百KB,而且它来回于每次请求之间,以很慢的响应时间阻挠着网站的访问者,且增加了服务器带宽的需求。
  • Page life cycle: The mechanism for 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 View State errors or finding that some event handlers mysteriously fail to execute.
    页面生命周期:连接客户端事件与服务器端事件处理代码的机制(是页面的部分生命周期)格外复杂和棘手。很少有开发者能够成功地维护控件层而不产生视图状态错误,或不发现某些事件处理程序莫明其妙地不能执行。
  • False sense of separation of concerns: ASP.NET’s code-behind model provides a means to take application code out of its HTML mark-up 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. The end result can be fragile and unintelligible.
    关注分离的错误理解:ASP.NET的后台代码模型提供了一种手段,把应用程序代码从它的HTML标记中提取出来,并放到一个独立的后台代码类中。这种逻辑与表现的分离得到了广泛的赞许,但在实际应用中,却又鼓励开发者在这些怪异的后台代码类中把表现代码(如维护服务器端控件树)与它们的应用程序逻辑(如维护数据库数据)混在一起。最终结果是脆弱和难以理解。
  • Limited control over HTML: Server controls render themselves as HTML, but not necessarily the HTML you want. Prior to ASP.NET 4, the HTML output usually failed to comply with web standards or make good use of CSS, and server controls generated unpredictable and complex ID values that are hard to access using JavaScript. These problems are reduced in ASP.NET 4, but it can still be tricky to get the HTML you expect.
    HTML上的受限控制:服务器控件把自己渲染成HTML,但并不是你所希望的必要的HTML。在ASP.NET 4之前,这种HTML输出通常不符合web标准,或不能很好地使用CSS,而且,服务器控件生成不可预知且复杂的ID值,结果,这些ID难以用JavaScript进行访问。这些问题在ASP.NET 4中减少了,但仍然不容易得到你所期望的HTML。
  • Leaky abstraction: Web Forms tries to hide away HTML and HTTP wherever possible. As you try to implement custom behaviors, you frequently fall out of the abstraction, which forces you to reverse-engineer the postback event mechanism or perform obtuse acts to make it generate the desired HTML. Plus, all this abstraction can act as a frustrating barrier for competent web developers.
    有缺陷的抽象:Web Form试图尽可能地隐去HTML和HTTP(这是通过Web Form的抽象层实现的——译者注)。当你试图实现自定义行为时,时常需要放弃这种抽象,这迫使你需要采取回发事件机制的逆向工程,或采取笨拙的方法(这样才可能绕过Web Form的抽象层,但这给编程造成了一定难度。——译者注),以使它生成所希望的HTML。再则,这种抽象可能对有能力的Web开发者构成一个极大的障碍(由于编程难度,给希望实现自定义行为的开发人员造成了一定困难。——译者注)。
  • Low testability: The designers of ASP.NET could not have anticipated that automated testing would become an essential component of software development. Not surprisingly, the tightly coupled architecture they designed is unsuitable for unit testing. Integration testing can be a challenge too, as we’ll explain in a moment.
    低可测试性:ASP.NET的设计者们未能预期到自动测试会成为软件开发的主要成分。毫不奇怪,他们设计的这种紧耦合体系结构不适合单元测试。集成测试也很具挑战性,我们马上会解释。

ASP.NET has kept moving. Version 2.0 added a set of standard application components that can 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. The most recent release, ASP.NET 4, produces more predictable and standards-compliant HTML markup, but many of the intrinsic limitations remain.
ASP.NET在不断改进。版本2.0添加了一组标准的应用程序组件,可以减少你需要编写的代码量。2007年发布的AJAX是微软对Web 2.0/AJAX疯狂时代的回应,它支持富客户端交互性而又保持使开发者的工作简单。最新版的ASP.NET 4能够产生更可预测且与标准兼容的HTML标记,但仍残留许多内在的局限性。

Web Development Today
当今的Web开发

Outside Microsoft, web development technology has been progressing rapidly and in several different directions since Web Forms was first released. Aside from AJAX, which we’ve already noted, there have been other major developments.
微软之外,自Web表单首次发布以来,web开发技术发展迅速,并表现在几个不同的方向。除了我们已经提及的AJAX之外,还有一些其它的主要发展。

Web Standards and REST
Web标准与REST

The drive for web standards compliance has increased in recent years. Web sites are consumed on a greater variety of devices and browsers than ever before, and web standards (for HTML, CSS, JavaScript, and so forth) remain our one great hope for enjoying a decent browsing experience everywhere—even on the Internet-enabled refrigerator. Modern web platforms can’t afford to ignore the business case and the weight of developer enthusiasm for web standards compliance.
向web标准靠拢近年来已经增强。Web网站建立在比以往更广泛的设备和浏览器之上,web标准(HTML、CSS、JavaScript等等)使我们有望能够在任何地方 — 甚至在可联网的冰箱上 — 都可以有相当好的浏览体验。现代web平台不可忽视商业环境和开发者对顺应web标准的挚爱。

At the same time, Representational State Transfer (REST) has become the dominant architecture for application interoperability over HTTP, completely overshadowing SOAP (the technology behind ASP.NET’s original approach to web services). REST describes an application in terms of resources (URIs) representing real-world entities and standard operations (HTTP methods) representing available operations on those resources. For example, you might PUT a new http://www.example.com/Products/Lawnmower or DELETE http://www.example.com/Customers/Arnold-Smith.
与此同时,表现式状态传输(REST)已经成为应用程序在HTTP上互操作的主要体系结构,完全使SOAP(ASP.NET原先进行web服务的支撑技术)黯然失色。REST根据表示真实世界实体的资源(URI)和表示在这些资源上可用的标准操作(HTTP方法)来描述一个应用程序。例如,你可能会PUT(传递)一个新的http://www.example.com/Products/Lawnmower,或DELETE(删除)http://www.example.com/Customers/Arnold-Smith。

Today’s web applications don’t serve just HTML; often they must also serve JSON or XML data to various client technologies including AJAX, Silverlight, and native smartphone applications. This happens naturally with REST, which eliminates the historical distinction between web services and web applications—but requires an approach to HTTP and URL handling that has not easily been supported by ASP.NET Web Forms.
当今的web应用程序不只服务于HTML,通常它们也必须把JSON或XML数据提供给各种客户端技术,包括AJAX、Silverlight,以及本地智能手机应用程序。利用REST,这会很自然地发生。REST消除了历史上web服务与web应用程序之间的差异 — 但这需要一种对HTTP和URL进行处理的办法,而这种办法对ASP.NET Web表单而言却难以得到支持。

Agile and Test-Driven Development
敏捷及测试驱动开发

It is not just web development that has moved on in the last decade—software development as a whole has shifted towards agile methodologies. This can mean a lot of different things, but it is largely about running software projects as adaptable processes of discovery, resisting the encumbrance and restrictions of excessive forward planning. Enthusiasm for agile methodologies tends to go hand in hand with a particular set of development practices—and tools (usually open source) that promote and assist these practices.
在过去的十多年中,不只web开发得到了发展 — 作为一个整体的软件开发,也朝着敏捷方法学方向前进。这可能意指许多不同的事情,但主要是指以发现、抵制阻碍和过分计划的自适应处理方式来运作软件项目。敏捷方法学的热情倾向于把一组特定的开发实践与促进和辅助这些实践的工具(通常是开源的)结合在一起。

Test-driven development (TDD), and its latest reincarnation, behavior-driven development (BDD), are two obvious examples. The idea is to design your software by first describing examples of desired behaviors (known as tests or specifications), so at any time you can verify the stability and correctness of your application by executing your suite of specifications against the implementation. There’s no shortage of .NET tools to support TDD/BDD, but these tend not to work well with Web Forms:
测试驱动开发(TDD),及其最新的化身,行为驱动开发(BDD)是两个明显的例子。其思想是,通过首先描述想得到的行为的范例(称为测试或规范)的方式来设计你的软件,所以,任何时刻,你都可以对你的实现执行一整套规范来验证你应用程序的稳定性和正确性。.NET支持TDD/BDD的工具并不缺乏,但它们几乎都不能与web表单很好地工作。

  • Unit testing tools let you specify the behavior of individual classes or other small code units in isolation. These can only be effectively applied to software that has been designed as a set of independent modules, so that each test can be run in isolation. Unfortunately, few Web Forms applications can be tested this way. Following the framework’s guidance to put logic into event handlers or even use server controls that directly query databases, developers typically end up tightly coupling their own application logic to the Web Forms runtime environment. This is death for unit testing.
    单元测试工具使你可以规定个别类或其它孤立的小型代码单元的行为。这些只能被有效地运用于被设计成一组独立模块的软件,以使得每个测试可独立地运行。不幸的是,很少有web表单应用程序能够以这种方式进行测试。根据(Web表单的)框架指南,要把逻辑放到事件处理程序中,或者甚至使用直接查询数据库的服务器控件,开发者最终典型地需要把自己的应用程序逻辑与web表单运行时环境紧紧地耦合在一起。这是不能进行单元测试的死结。
  • UI automation tools let you simulate a series of user interactions against a complete running instance of your application. These can in theory be used with Web Forms, but they can break down whenever you make a slight change to your page layout. Without special attention, Web Forms starts generating totally different HTML structures and element IDs, rendering your existing test suite useless.
    UI自动化工具使你能够根据应用程序的一个完整的运行实例来模拟一系列用户交互。这在理论上可以用于Web表单,但当你对页面布局作微小改动时,它们都可能会崩溃。如果不特别小心,web表单就会生成完全不同的HTML结构和元素的ID值,导致你正使用的测试套件失效。

The .NET open source and independent software vendor (ISV) community has produced no end of top-quality unit testing frameworks (NUnit, xUnit), mocking frameworks (Moq, Rhino Mocks), inversion-of-control containers (Ninject, AutoFac), continuous integration servers (Cruise Control, TeamCity), object-relational mappers (NHibernate, Subsonic), and the like; and proponents of these tools and techniques have found a common voice, publishing and organizing conferences under the shared brand ALT.NET. Traditional ASP.NET Web Forms is not amenable to these tools and techniques because of its monolithic design, so from this vocal group of experts and industry thought leaders, Web Forms gets little respect.
.NET开源和独立的软件厂商团体已经生产了无数顶级质量的单元测试框架(NUnit、xUnit)、模仿框架(Moq、Rhino Mocks)、控制反转容器(Ninject、AutoFac)、连续累计服务器(Cruise Control、TeamCity)、对象关系映射器(NHibemate、Subsonic)等等。而且这些工具和技术的建议者们已经在共享商标ALT.NET下形成了共同的意见、发表并组织会议。传统的ASP.NET Web表单由于它的单片式设计,不服从于这些工具和技术。因此,这在专家团体和行业思想领导者们的眼中,Web表单没能得到起码的尊重。

Ruby on Rails

In 2004, Ruby on Rails was a quiet, open source contribution from an unknown player. Suddenly fame hit, transforming the rules of web development. It’s not that it contained revolutionary technology, but that it took existing ingredients and blended them in such a compelling and appealing way as to put existing platforms to shame.
2004年Ruby on Rails还默默无闻,只是一个无名倡导者的开源项目。突然声名鹤唳,转变着web开发的规则。并不是它包含了革命性的技术,而是它利用了已有的成分,并把它们掺和成一种引人注目的方式,而使现有的平台感到羞愧。

Ruby on Rails (or just Rails as it is commonly called) embraced a model-view-controller (MVC) architecture. Don’t worry if you are not familiar with the MVC pattern—we’ll explain the details as we go. By applying MVC and 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 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 and now the war was over. Rails shows that web standards compliance and RESTfulness don’t have to be hard. It also shows that agile development and TDD work best when the framework is designed to support them. The rest of the web development world has been catching up ever since.
Ruby on Rails(或通常所说的Rails)采纳了一种模型-视图-控制器体系结构。如果你不熟悉MVC模式,不必着急 — 我们接下来会详细解释。通过运用MVC并配合而不是违背HTTP协议进行工作、用发扬约定代替需要配置、以及把对象关系映射(ORM)工具集成到它的内核等,Rails应用程序或多或少都能循序渐进而无需太多努力。就好像web开发一直就应该是这样,好像我们突然地意识到,所有这些年我们都是在进行工具战争,而现在,战争结束了。Rails表明,顺应web标准和REST化并不困难。它也表明,当框架支持敏捷开发与TDD时,它们工作是最好的。从那时起,整个web开发世界都被调动起来了。

Sinatra

Thanks to Rails, there were soon a lot of web developers using Ruby as their main programming language. But in such an intensively innovative community, it was only a matter of time before alternatives to Rails would appear. The best known, Sinatra, emerged in 2007.
感谢Rails,很快有很多web开发者以Ruby作为他们的主要编程语言。但在当今这样一个有强烈创新意识的社会中,出现Rails的替代品只是时间问题。最著名的Sinatra于2007年问世了。

Sinatra discards almost all of the standard Rails-style infrastructure (routing, controllers, views, etc.) and merely maps URL patterns to Ruby code blocks. A visitor requests a URL, which causes a Ruby code block to be executed and data is sent back to the browser—that’s it. It’s an incredibly simple kind of web development, but it’s found a niche in two main areas. First, for those building RESTful web services, it just gets the job done fast (we touch upon REST in Chapter 14). Second, since Sinatra can be connected to an extensive range of open source HTML templating and ORM technologies, it’s often used as a foundation on which to assemble a custom web framework to suit the architectural needs of whatever project is at hand.
Sinatra摒弃了几乎所有标准的Rails风格的基础结构(路由、控制器、视图等),而仅把URL模式映射到Ruby代码块。一个访问者请求一个URL,这会引起执行一个Ruby代码块,并把数据送回浏览器 — 这就行了。这是一个难以置信的简单的web开发形式,但它只在两个主要方面奠定了一个小环境。第一,对那些建立REST化的web服务,它恰好能快速完成工作(我们在第14章简单涉及REST)。第二,由于Sinatra可以连接广泛的开源HTML模板和ORM技术,通常以此为基础来装配一个自定义的web框架,以适应手头各种项目的体系结构需求。

Sinatra has yet to take any serious market share from full-stack MVC platforms like Rails (or ASP.NET MVC). We mention it here simply to illustrate the Web development industry’s ongoing trend towards simplification, and because Sinatra acts as an opposing force against other frameworks amassing ever more core features.
Sinatra还需要从大堆的MVC平台如Rails(或ASP.NET MVC)中占据大片的市场份额。我们在这里简单地提到它,只是想勾画web开发行业正在朝着简化的方向发展,也因为Sinatra起到对抗其它框架(甚至聚集了更核心的特性)的作用。

Node.js

Another significant trend is the movement toward using JavaScript as a primary programming language. Ajax first showed us that JavaScript is important; jQuery showed us that it could be powerful and elegant; and Google’s open source V8 JavaScript engine showed us that it could be incredibly fast. Today, JavaScript is becoming a serious server-side programming language. It serves as the data storage and querying language for several nonrelational databases including CouchDB and Mongo, and it’s used as a general purpose language in server-side platforms such as Node.js.
另一个明显的趋势是朝着以JavaScript作为主要编程语言的方向发展。Ajax向我们展示了JavaScript是重要的,jQuery向我们展示了它功能强大而雅致,而Google的开源V8 JavaScript引擎则向我们展示了它可能难以置信地快速。如今,JavaScript正在成为一种重要的服务器端编程语言。它为一些非关系型数据库,包括CouchDB和Mongo等,提供数据存储和查询语言服务,并被用作为服务器端平台的一种通用语言,如Node.js。

Node.js has been around since 2009 and gained wide acceptance very quickly. Architecturally it’s similar to Sinatra, in that it doesn’t apply the MVC pattern—it is a more low-level way of connecting HTTP requests to your code. Its key innovations are:
Node.js自2009年出现,并很快得到了广泛的接受。体系结构上,它类似于Sinatra,因为它不运用MVC模式 — 它以更低级的方式把HTTP请求连接到你的代码。其关键创新是:

  • Using JavaScript: Developers then need work only in a single language, from client-side code, through server-side logic, and even into data querying logic via CouchDB or the like.
    使用JavaScript:开发者于是只需要以一种语言进行工作,从客户端代码到服务器端逻辑,甚至是对CouchDB或之类的数据查询逻辑。
  • Being completely asynchronous: Node.js’s API simply doesn’t expose any way of blocking a thread while waiting for input or output (I/O) or any other operation. All I/O is implemented by beginning the operation, and then later receiving a callback when the I/O is completed. This means that Node.js makes extremely efficient use of system resources, and may handle tens of thousands of concurrent requests per CPU (alternative platforms tend to be limited to about 100 concurrent requests per CPU).
    是完全异步的:在等待输入或输出(I/O)或任何其它操作时,Node.js的API根本不会显露出任何方式的线程阻塞。通过启动其操作,然后在该I/O完成时接收一个回调便实现一个完整的I/O操作。这意味着Node.js形成了非常有效的系统资源利用,使得每CPU可能处理数以万计的并发请求(其它平台只能期望把每CPU并发请求限制在100左右)。

Like Sinatra, Node.js is a niche technology. Most businesses building real applications in limited timescales critically need all the infrastructure in full-stack frameworks like Ruby on Rails and ASP.NET MVC. We describe Node.js here only to put some of ASP.NET MVC’s design into context against industry trends. For example ASP.NET MVC includes asynchronous controllers (which we describe in Chapter 14). This is a way to handle HTTP requests with non-blocking I/O and scale up to handle more requests per CPU. And as you’ll learn, ASP.NET MVC integrates very well with sophisticated JavaScript code running in the browser (which we introduce in Chapters 18, 19 and 20)
像Sinatra一样,Node.js是一种小环境技术。在有严格时间限制的情况下,建立实际应用程序的大多数事务一般都需要诸如Ruby on Rails,ASP.NET MVC等,这种全技术堆栈框架的全部基础架构。我们在这里描述Node.js,只是把某些ASP.NET MVC的设计放入工业趋势的情形之中。例如,ASP.NET MVC包含了异步控制器(第14章描述)。这就是一种以非阻塞I/O处理HTTP请求、并提高每CPU处理更多请求的方式。而且,正如你将了解到的,ASP.NET MVC很好地集成了运行在浏览器端的成熟的JavaScript代码(将在第18、19、20章介绍)。

Key Benefits of ASP.NET MVC
ASP.NET MVC的关键优点

ASP.NET has been a great commercial success, but as discussed, the rest of the web development world has moved on, and even though Microsoft has kept dusting the cobwebs off Web Forms, its essential design has started to look quite antiquated.
ASP.NET已经获得了巨大的商业成功,但正如所讨论的,其它web开发界也在进步,即使微软,也在不断清理Web表单的垢病,因为其基本设计看上去已经相当陈旧了。

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 the core ASP.NET platform, clearly designed as a direct response to the evolution of technologies such as Rails and as a reaction to the criticisms of Web Forms. The following sections show how this new platform overcame the Web Forms limitations and brought ASP.NET back to the cutting edge.
2007年10月,在德克萨斯-奥斯汀的第一次ALT.NET国际会议上,微软副总裁Scott Guthrie宣布并演示了崭新的MVC web开发平台分支,它建立在ASP.NET平台核心之上,明确地作出对诸如Rails等的技术进展直接回应,以及对Web表单批评的反应。以下小节说明这个新平台如何克服Web表单的局限性,并把ASP.NET重新带回到先进行列。

MVC Architecture
MVC的体系结构

It’s important to distinguish between the MVC architectural pattern and the MVC Framework. The MVC pattern isn’t new—it dates back to 1978 and the Smalltalk project at Xerox PARC—but it’s gained enormous popularity today as an architecture for web applications, for the following reasons:
重要的是区别MVC体系结构模式与MVC框架。MVC模式并不新 — 这要回溯到1978年Xerox PARC的Smailltalk项目 — 但它作为一种web应用程序的体系结构,如今已得到了巨大的普及,原因如下:

  • User interaction with an MVC application follows a natural cycle: the user takes an action, and 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.
    用户与MVC应用程序的交互遵循一种自然周期:用户采取一个动作,应用程序对之做出响应,以修改其数据模型,并把一个更新的视图提供给该用户。然后重复这一周期。这非常适合于以一系列HTTP请求与响应进行传递的web应用程序。
  • Web applications necessitate combining several technologies (databases, HTML, and executable code, for example), usually split into a set of tiers or layers. The patterns that arise from these combinations map naturally onto the concepts in MVC.
    Web应用程序必须组合多种技术(如数据库、HTML、可执行代码等等),这通常分成一组层次。这些组合所产生的设计模式自然地映射到了MVC的概念上。

The ASP.NET MVC Framework implements the MVC pattern—and in doing so provides greatly improved separation of concerns. In fact, ASP.NET MVC implements a modern variant of MVC that’s especially suitable for web applications. You’ll learn more about the theory and practice of this architecture in Chapter 4.
ASP.NET MVC框架实现了这种MVC模式 — 而且极大地改善了关注分离。事实上,ASP.NET MVC实现了MVC的现代化的变异,它特别适用于web开发的MVC。你将在第4章更多地了解这种体系结构的理论与实践。

By embracing and adapting the MVC pattern, the ASP.NET MVC framework provides strong competition to Ruby on Rails and similar platforms, and brings the MVC pattern into the mainstream of the .NET world. By capitalizing on the experience and best practices discovered by developers using other platforms, ASP.NET MVC has, in many ways, pushed forward beyond what even Rails can offer.
通过采纳和调整MVC模式,ASP.NET MVC框架形成了对Roby on Rails以及类似平台强有力的竞争,并把MVC模式带到了.NET世界的主流。利用开发人员使用其它平台的体验和最优方法,ASP.NET MVC在许多方面的推进甚至已经超越了Rails。

Extensibility
可扩展性

Your desktop PC’s internal components are independent pieces that interact only across standard, publicly documented interfaces. 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. The MVC Framework is also built as a series of independent components—satisfying a .NET interface or built on an abstract base class—so you can easily replace components such the routing system, the view engine, the controller factory, and so on, with a different one of your own implementation. The ASP.NET MVC designers set out to give you three options for each MVC Framework component:
桌面电脑的内部组件是一个个独立的部件,它们只通过标准的公共文档接口进行交互。你可以很容易地拔出显卡或硬盘,并用另一制造商的来替换,相信它会在插槽中正常工作。MVC框架也被构建成一系列独立的组件 — 满足一个.NET接口,或建立在一个抽象类之上 — 因此,你可以很容易地用一个自己的不同实现来替换相应组件,如,替换路由系统、视图引擎、控制器工厂等等。ASP.NET MVC设计者对每一个MVC框架组件都为你提供了三种选择:

  • Use the default implementation of the component as it stands (which should be enough for most applications).
    使用组件现行的默认实现(它应该足以满足大多数应用程序)。
  • Derive a subclass of the default implementation to tweak its behavior.
    派生默认实现的一个子类,以调整其行为。
  • 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 in Chapter 10.
这就像自ASP.NET 2.0开始的提供器模型一样,但采取了更大的进步 — 深入到了MVC框架的核心部分。从第10章开始,你将了解所有这些各种各样的组件,以及如何和为什么要调整或替换这些组件。

Tight Control over HTML and HTTP
在HTML及HTTP上的密切控制

ASP.NET MVC recognizes the importance of producing clean, standards-compliant markup. Its built-in HTML helper methods produce standards-compliant output—but there is a more significant philosophical change compared with Web Forms. Instead of spewing out huge swathes of HTML over which you have little control, the MVC Framework encourages you to craft simple, elegant markup styled with CSS.
ASP.NET MVC认识到产生干净的、标准兼容的标记的重要性。其内建的HTML辅助器方法产生标准兼容的输出 — 但与Web表单相比,有更重要的完善变革。替代原先那种喷出大片你无法控制的HTML标记,MVC框架鼓励你构思简单、雅致的可设置CSS样式的标记。

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 easy to use best-of-breed UI libraries such as jQuery or the Yahoo UI Library. JavaScript developers will be pleased 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, and even lets you directly reference the jQuery .js file on Microsoft’s own Content Delivery Network (CDN) servers. We cover jQuery in Chapter 20.
当然,如果你确实想对复杂UI元素使用一些现成的部件,如,日期选择器或级联菜单等,ASP.NET MVC的“无特殊需求”标记方法可以很容易地使用最佳品种UI库,如jQuery库或Yahoo UI库等。JavaScript开发者如果了解到,微软已经把jQuery装配为默认ASP.NET MVC项目模板的一个内建部件,ASP.NET MVC与通用jQuery库啮合得如此良好,而且,甚至让你能够直接引用微软自己的内容分发网络(CDN)服务器上的jQuery的.js文件,他们会感到非常开心。我们在第20章讨论jQuery。

ASP.NET MVC–generated pages don’t contain any View State data, so they can be hundreds of kilobytes smaller than typical pages from ASP.NET Web Forms. Despite today’s fast broadband connections, this economy of bandwidth still gives an enormously improved end user experience.
ASP.NET MVC生成的页面不含任何视图状态数据,因此,这些网页可能比典型的ASP.NET Web表单页面要小几百KB。无论今天的快速带宽如何,这种经济带宽仍然极大地改善了终端用户的体验。

Like Ruby on Rails, ASP.NET MVC works in tune with HTTP. You have total control over the requests passing between browser and server, so you can fine-tune your user experience as much as you like. Ajax is made easy, and there aren’t any automatic post-backs to interfere with client-side state—any developer who primarily focuses on the Web will almost certainly find this to be hugely freeing and the workday more satisfying.
与Ruby on Rails一样,ASP.NET MVC与HTTP工作十分协调。你对传递于浏览器与服务器之间的请求有完全的控制,因此只要愿意,你可以仔细地调节用户体验。Ajax很容易使用,而且没有任何自动回递扰乱客户端状态 — 任何主要关注于Web的开发人员几乎肯定会发现这是极大的解放,且让人工作愉快。

Testability
可测试性

The MVC architecture gives you a great start in making your application maintainable and testable, because you naturally separate different application concerns into different, independent software pieces.
MVC体系结构为你提供了很棒的起点,以使你的应用程序可维护和可测试,因为你自然地把应用程序的不同关注分成了不同的、独立的软件片段。

Yet the ASP.NET MVC designers didn’t stop there. To support unit testing, they took the framework’s component-oriented design and made sure that each separate piece is structured to meet the requirements of unit testing and mocking tools.
ASP.NET MVC的设计者们还不止做了这些。为了支持单元测试,他们对该框架采取了面向组件的设计,并确保把每个独立的片段构造成满足单元测试和模仿工具的需求。

They added Visual Studio wizards to create starter unit test projects on your behalf, which are integrated with open-source unit test tools such as NUnit and xUnit, as well as Microsoft’s own MSTest. Even if you’ve never written a unit test before, you’ll be off to a great start.
他们添加了Visual Studio向导,为你创建初步的单元测试项目,该项目集成了开源的单元测试工具,如NUnit和xUnit,以及微软自己的MSTest。即使你以前从未写过单元测试,你也会有一个很好的开始。

Throughout this book, you’ll see examples of how to write clean, simple unit tests for ASP.NET MVC controllers and actions that supply fake or mock implementations of framework components to simulate any scenario, using a variety of testing and mocking strategies.
整个这本书你都会看到,如何为ASP.NET MVC的控制器以及动作编写干净、简单的单元测试。这些单元测试使用各种测试和模仿策略,提供对框架组件的伪造或模仿实现来模拟各种情景。

Testability is not only a matter of unit testing—ASP.NET MVC applications work well with UI automation testing tools, too. You can write test scripts that simulate user interactions without having to guess what HTML element structures, CSS classes, or IDs the framework will generate, and you don’t have to worry about the structure changing unexpectedly.
可测试性并不仅仅是单元测试的事情 — ASP.NET MVC应用程序也与UI自动操作测试工具协作良好。你可以编写模拟用户交互的脚本,而不必猜测框架会生成什么样的HTML元素结构、什么样的CSS的class、或什么样的ID等等,也不必担忧结构的意外变化。

Powerful Routing System
强大的路由系统

The style of URLs has evolved as web application technology has improved—URLs like this one:
随着web应用程序技术的改进,URL样式已经产生了演变 — 像这样的URL:

/App_v2/User/Page.aspx?action=show%20prop&prop_id=82742

are increasingly rare, replaced with a simpler, cleaner format such as this:
明显罕见了,代之以一种更简单、更清晰的格式,像这样:

/to-rent/chicago/2303-silver-street

There are some good reasons for caring about the structure of URLs. First, 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 simpler URL. Second, 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. Third, when someone understands the structure of a URL, they’re more likely to link to it, share it with a friend, or even read it aloud over the phone. Fourth, it doesn’t expose the technical details, folder, and file name structure of your application to the whole public Internet, so you’re free to change the underlying implementation without breaking all your incoming links.
考虑这种URL结构有一些很好的理由。首先,搜索引擎对一个URL中找到的关键词有明显的权重。一个对“芝加哥租房”的搜索,更可能找到的是一个较简单的URL。其次,许多web用户现在对一个URL有了足够的领悟,并且欣赏在浏览器的地址栏中输入导航选项。第三,当某人理解了URL的结构时,他们更可能连接它、与朋友共享它、或在电话中报读它。第四,它并不会把你应用程序的技术细节、文件夹、文件名结构暴露给整个公用网,因此,你可以自由地修改底层实现而不会打断输入连接。

Clean URLs were hard to implement in earlier frameworks, but ASP.NET MVC uses the System.Web.Routing facility to give you clean URLs by default. This gives you control over your URL schema and its relationship to your application—giving you the freedom to create a pattern of URLs that is meaningful and useful to your users, without the need to conform to a predefined pattern. And, of course, this means you can easily define a modern REST-style URL schema if you wish.
整洁的URL在早期的框架中难以实现,但ASP.NET MVC默认使用System.Web.Routing工具给出整洁的URL。这使你能够完全控制URL方案及其与应用程序的关系 — 使你能自由地创建对用户有意义和有用的URL模式,而无需符合预定义模式。而且当然,这意味着如果你想,你可以很容易地定义现代的REST风格的URL方案。

Tip You’ll find a thorough treatment of routing and URL best practices in Chapter 11.
提示:你将在第11章找到路由的整个处理和URL最佳实践。

Built on the Best Parts of the ASP.NET Platform
建立在ASP.NET平台最好的部分之上

Microsoft’s existing ASP.NET platform provides a mature, well-proven set of components and facilities for developing effective and efficient web applications.
微软现在的ASP.NET平台为高效开发web应用程序提供了一组成熟的、经充分证明的组件和工具集。

First and most obviously, since ASP.NET MVC is based on the .NET 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.
首先,也是最明显的,由于ASP.NET MVC是基于.NET平台的,因此你拥有了很大的灵活性,你可以使用任何.NET语言来编写代码、可以访问同样的API特性 — 这不仅仅是MVC本身的特性,而是广泛的.NET类库、以及广泛的第三方.NET包库体系。

Second, ready-made ASP.NET platform features, such as master pages, forms authentication, membership, roles, profiles, and internationalization can reduce the amount of code you need to develop and maintain any web application—and these features are just as effective when used in the MVC Framework as they are in a classic Web Forms project. Some Web Forms’ 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 Web Forms–specific notions such as View State).
其次,现成的ASP.NET平台特性,如母版页、表单认证、成员、角色、特征、以及国际化等等,可以减少你开发和维护web应用程序的代码量 — 而且这些特性在MVC框架中的使用就像它们在经典的web表单项目中的使用一样有效。一些Web表单内建的服务器控件 — 以及你的早期项目中的自定义控件 — 可以在一个ASP.NET MVC应用程序中被重用(只要它们不依赖于Web表单的专用概念,如视图状态)。

Development and deployment are covered, too. Not only is ASP.NET tightly integrated into Visual Studio, it’s the native web programming technology supported by the IIS web server built into Windows XP, Vista, 7, and Server products. IIS, since version 7, gives first-class support to .NET managed code as a native part of its request-handling pipeline, with special treatment for ASP.NET applications. Being built on the core ASP.NET platform, MVC applications get all these benefits. Chapter 23 explains what you need to know to deploy ASP.NET MVC applications to IIS on Windows Server.
也涉及开发与部署。ASP.NET不仅被紧密地集成到了Visual Studio之中,它也是建立在Windows XP、Vista、Win 7、以及Server产品中的IIS web服务器所支持的本地web编程技术。IIS自第7版起,利用对ASP.NET应用程序的特殊处理,可以把.NET托管代码作为其请求处理管道的本地部件,实现了对.NET托管代码的一流支持。由于建立在ASP.NET平台的核心之上,MVC应用程序得到了所有这些好处。第23章解释你需要了解的知识,以便把ASP.NET MVC应用程序部署到Windows Server的IIS上。

Modern API
现代API

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.
自2002年初,微软的.NET平台经过了不懈的演变,它现在在许多方面支持、甚至定义了达到最新技术发展水平的现代编程。

ASP.NET MVC 3 is built for .NET 4, so its API can take full advantage of recent language and runtime innovations—including extension methods, lambda expressions, anonymous and dynamic types, and LINQ. Many of the MVC Framework’s API methods and coding patterns follow a cleaner, more expressive composition than was possible with earlier platforms.
ASP.NET MVC 3是针对.NET 4而建立的,因此它的API可以充分利用最新语言和运行时创新 — 包括扩展方法、lambda表达式、匿名及动态类型、以及LINQ等等。许多MVC框架的API方法和编码模式与早期平台相比,遵循了一种更清晰、更富表现力的写作方式。

ASP.NET MVC Is Open Source
ASP.NET MVC是开源的

Unlike with previous Microsoft web development platforms, you’re free to download the original source code for ASP.NET MVC and even modify and compile your own version of it. This is invaluable when your debugging trail leads into a system component and you want to step into its code (and even read 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.
与之前的微软web开发平台不同,现在你可以自由地下载ASP.NET MVC的源代码,并且甚至修改和编译你自己的版本。当你的调试深入到系统组件,并且你想步入其代码内部(甚至读取源程序员的注释),以及,如果你正在建立高级组件,并想看看有些什么开发可能性,或者想了解内建组件如何工作等等情况时,这种开源是无价的。

Of course, this ability is also great if you don’t like the way something works, if you find a bug, or if you 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. ASP.NET MVC is licensed under Ms-PL (www.opensource.org/licenses/ms-pl.html), an Open Source Initiative (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, Microsoft does not accept patches to the official build. At present, Microsoft will only ship code that’s the product of its development and QA teams. You can download the MVC source code from http://aspnet.codeplex.com/.
当然,如果你不喜欢框架的某些工作方式、如果你发现了一个缺陷、或者如果你恰恰想访问一些不能访问的东西,开源都是很棒的,因为你可以自己做一些简单的修改。然而,你需要对你的修改保持跟踪,并在你想更新到框架的新版本时,把它们重新运用起来。ASP.NET MVC工作在Ms-PL许可之下(www.opensource.org/licenses/ms-pl.html),这是一个开放源代码倡议(OSI)核准的开源许可协议,意即,你可以修改源码、部署它、甚至把你的修改公开作为派生项目重新分发。然而,微软不接受对其官方产品的补丁。目前,微软只提供其开发团队和QA团队的产品代码。你可以从http://aspnet.codeplex.com/上下载MVC源代码。

Who Should Use ASP.NET MVC?
谁该使用ASP.NET MVC?

As with any new technology, the fact of its existence isn’t a compelling reason to adopt it. In the following sections, we’ll give you our view of how the MVC Framework compares with the most obvious alternatives. We’ve tried to be as unbiased as two people writing a book about the MVC Framework can be—but we know that there is a limit to our objectivity. The following sections are technology-based comparisons. When selecting a web application framework, you should also consider the skills of your team, the work involved in porting any existing projects, and your relationship with, and confidence in, the technology source.
如同任何新技术一样,因为其存在就必须使用它,这并不是一个充分的理由。在以下小节中,我们将给出MVC框架与大多数流行的替代品比较所得到的我们的观点。我们作为编写一本关于MVC框架书籍的人,力图做到没有偏见 — 但我们知道,这受限于我们的客观情况。以下小节是基于技术的比较。当选择一个web应用程序框架时,你也应当考虑:在技术层面上,你团队的技能、移植现有项目所涉及的工作、你的关系、以及信心等方面的因素。

Comparisons with ASP.NET Web Forms
与ASP.NET Web表单的比较

We have already detailed the weaknesses and limitations in traditional ASP.NET Web Forms, and how ASP.NET MVC overcomes many of those problems. That doesn’t mean that Web Forms is dead, though; Microsoft has repeatedly stated that both technologies are being actively developed and actively supported, and that there are no plans to retire Web Forms. In some ways, your choice between the two is a matter of development philosophy.
我们已经详述了传统ASP.NET Web表单的弱点与局限性,以及ASP.NET MVC如何克服了这些问题的许多方面。但这并不意味着Web表单的消亡,微软反复声明,对这两种技术都会积极地加以发展和支持,而且也没有要引退Web表单的计划。在某些方面,你对两者的选择是一种开发理念方面的事情。

  • Web Forms takes the view that UIs should be stateful, and to that end adds a sophisticated abstraction layer on top of HTTP and HTML, using View State and post-backs 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.
    Web表单的观念是UI应当是状态化的,并最终在HTTP和HTML之上添加一个复杂的抽象层,用视图状态和回递来创建状态化的效果。这使得它适合于“拖-放”式Windows表单风格的开发,其间,你把UI部件拖放到一个画布上,并在其中填写其事件处理器的代码。
  • 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, modern approach to writing web applications, with tidy code that’s easier to extend and maintain over time, and that’s free of bizarre complications and painful limitations.
    MVC采纳了HTTP真正的无状态本性,遵循而不是违抗它。它要求你理解web应用程序实际上是如何工作的,在理解的提前下,它提供了一种简单的、功能强大的、现代的方法,以整洁的代码来编写web应用程序,这些代码总是易于扩展和维护,并且免除了离奇的复杂性和令人痛苦的限制。

There are certainly cases where Web Forms 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. Web Forms’ drag-and-drop development strengths can outweigh its weaknesses when you don’t have to worry about bandwidth consumption or search engine optimization.
当然也有Web表单至少与MVC一样、甚至更好的一些情况。明显的例子是开发小型的、企业内部型应用程序,它大量的工作是把网格直接绑定于数据库表或通过向导对用户进行引导。当你不必担忧带宽消耗或搜索引擎优化时,Web表单的拖-放式开发优点可能胜过它的弱点。

If, on the other hand, you are writing applications for the Internet, or larger intranet applications, you will be attracted by the bandwidth efficiencies, better browser compatibility, and better support for automated testing that MVC offers.
另一方面,如果你正在编写用于Internet的应用程序,或大型intranet应用程序,那么你会被MVC所提供的带宽效率、更好的浏览器兼容性、以及更好的自动测试支持等所吸引。

Migrating from Web Forms to MVC
从Web表单迁移到MVC

If you have an existing ASP.NET Web Forms project that you are considering migrating to MVC, you will be pleased to know that the two technologies can coexist in the same application. This provides an opportunity to migrate existing applications gradually, especially if the application is partitioned into layers with domain model or business logic constrained separately to the Web Forms pages. In some cases you might even deliberately design an application to be a hybrid of the two technologies.
如果你正在考虑把一个现存的ASP.NET Web表单项目迁移到MVC,你会开心地了解到,这两种技术可以并存于同一个应用程序之中。这为逐步迁移现存的应用程序提供了机会,特别是,利用域模型或事务逻辑单独地对Web表单的页面进行约束,而把应用程序分成若干层次的情况,尤其如此。在有些情况下,你甚至可以故意把一个应用程序设计成混用两种技术。

Comparisons with Ruby on Rails
与Ruby on Rails的比较

Rails has become a benchmark against which other web platforms are compared. Developers and companies who are in the Microsoft .NET world will find ASP.NET MVC far easier to adopt and learn, whereas developers and companies that work in Python or Ruby on Linux or Mac OS X will find an easier path to 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已经成为与其它web平台进行比较的一个基准。微软.NET世界的开发者和公司会发现ASP.NET MVC易于使用和学习,而工作于Linux或Mac OS X上的Python或Ruby开发者和公司会发现Rails更容易。从Rails迁移到ASP.NET MVC是不可能的,反之亦然。两种技术之间有一些本质上的差别。

Rails is a holistic development platform, meaning that it handles the complete stack, right from database source control, through ORM, to handling requests with controllers and actions, all topped off with built-in automated testing tools.
Rails是一种整体开发平台,意即,它处理整个技术堆栈,从通过ORM进行数据库源控制,到用控制器和动作处理请求,所有一切都可以用内建的自动测试工具来完成。

The ASP.NET MVC Framework focuses on handling web requests in an MVC-pattern with controllers and actions. It does not have a built-in ORM tool, a built-in automated testing tool, or a system for managing database migrations—this is because the .NET platform already has an enormous range of choices for these functions, and you can use any of them. For example, if you’re looking for an ORM tool, you might use NHibernate, Subsonic, Microsoft’s Entity Framework, or one of the many other mature solutions available. Such is the luxury of the .NET platform—though this does mean that these components are not as tightly integrated into ASP.NET MVC as the equivalents are into Rails.
ASP.NET MVC框架关注于以MVC模式用控制器和动作来处理web请求。它不具有内建的ORM工具、内建的自动测试工具、或管理数据库迁移的系统 — 这是因为.NET平台已经对这些功能包含了广泛的可选范围,而且你可以使用其中任意一种。例如,如果你正寻找一个ORM工具,你可以用NHibernate、Subsonic、微软的实体框架、或其它任意一种成熟可用的解决方案。这就是宽松的.NET平台 — 尽管它实际意味着这些组件确实并未像Rails那样集成到ASP.NET MVC之中。

Comparisons with MonoRail
与MonoRail的比较

MonoRail is an earlier .NET-based MVC web application platform—created as part of the open source Castle project and has been in development since 2003. In many ways, MonoRail acted as the prototype for ASP.NET MVC—MonoRail demonstrated how a Rails-like MVC architecture could be built on top of ASP.NET and established patterns, practices, and terminology that are used throughout Microsoft’s implementation.
MonoRail是一个早期的基于.NET MVC的web应用程序平台 — 是自2003年作为开源项目Castle的一部分来创建和开发的。在许多方面,MonoRail就像ASP.NET MVC的原型 — MonoRail演示了如何在ASP.NET上建立一个类似于Rails的MVC体系结构,并完全使用微软的实现来建立要运用的模式、实践、和术语等。

We don’t see MonoRail as a serious competitor. It is probably the most popular .NET web application platform created outside Redmond, and it did achieve reasonably widespread adoption in its day—but since the launch of ASP.NET MVC, the MonoRail project is rarely heard of. The momentum of enthusiasm and innovation in the .NET web development world is now focused on ASP.NET MVC.
我们未把MonoRail看作为一个严格的竞争者。这可能是雷德蒙德(微软总部 — 译者注)之外创建的最流行的.NET web应用程序平台,而且在它的日子里确实取得了相当广泛的采纳 — 但自从ASP.NET MVC发布之后,已经很少听到MonoRail项目的消息了。.NET web开发领域的狂热和创新势头现在主要集中在ASP.NET MVC上。

What’s New in ASP.NET MVC 3
ASP.NET MVC 3的新特性

The headline feature in MVC version 3 is the introduction of the Razor View Engine. Previous versions of MVC have relied on the standard ASP.NET view engine, which depends on the ASP.NET <% and %> blocks—if you have done any kind of ASP.NET development, you are certain to have seen these in use.
MVC 3版的主要特性是引入了Razor视图引擎。以前的MVC版本一直依赖于ASP.NET的视图引擎,它依赖于ASP.NET的<%和%>代码块 — 如果你曾做过任意一种ASP.NET开发,你肯定看到过这种运用。

The Razor engine replaces the traditional blocks with the @ character. The new notation is quicker to write, faster to compile, has more flexible features and allows for better unit testing than the old view engine. You can still use the previous approach, but the Microsoft team has made it clear that Razor is the future for MVC—so much so, that we have used Razor for all of the examples in this book.
Razor引擎用@字符代替了传统的代码块。这种新符号能更快地书写、更快地编译、具有更灵活的特性,并比旧的视图引擎更易于单元测试。你仍然可以使用以前的方法,但微软团队已经清楚地表明,Raozr是MVC的未来 — 所以,我们对本书中的示例都采用了Razor。

Razor isn’t the only enhancement in MVC 3—the Visual Studio project tooling has been streamlined, there is better support for dependency injection, and improved support for the JSON data format and JavaScript—including tighter integration with jQuery.
MVC 3的增强并不只是Razor — Visual Studio项目工具也已经作了改进,对依赖性注入有更好的支持,而且改善了对JSON数据格式以及对JavaScript的支持 — 包括与jQuery的紧密集成。

Summary
小结

In this chapter, we have seen how web development has evolved at tremendous speed from the primordial swamp of the CGI executable to the latest high-performance, standards-compliant, agile platforms. We reviewed the strengths, weaknesses, and limitations of ASP.NET Web Forms, Microsoft’s main web platform since 2002, and the changes in the wider web development industry that forced Microsoft to respond with something new.
本章中,我们已经看到了web开发如何高速演变,从CGI可执行程序的原始沼泽到最新的高性能、标准兼容、敏捷平台。我们回顾了微软自2002开始就在使用的主流web平台ASP.NET Web表单的强项、弱点和局限性,以及迫使微软用一些新事物对其作出响应的广泛的web开发行业的变革。

We saw how the ASP.NET MVC platform addresses the weaknesses of ASP.NET Web Forms, and how its modern design delivers advantages to developers who want to write high-quality, maintainable code. In the next chapter, you’ll see the MVC Framework in action, learning the simple mechanisms that yield all these benefits. By Chapter 7, 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.
我们看到了ASP.NET MVC平台如何解决ASP.NET Web表单的弱点,以及它的现代设计如何把优势交付给那些想编写高质量、可维护代码的开发者。在下一章中,你将看到MVC框架的运转、了解获得所有这些好处的一些简单机制。到第7章,你便做好了以整洁的体系结构、适当的关注分离、自动测试、以及漂亮的最少标记来建立一个真实的电子商务应用程序的各项准备。


看完此文如果觉得有所收获,请给个推荐

posted @ 2012-04-17 06:15  r01cn  阅读(9106)  评论(25编辑  收藏  举报