Tải bản đầy đủ (.pdf) (590 trang)

Programming Microsoft ASP.NET MVC pdf

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (14 MB, 590 trang )

PUBLISHED BY
Microsoft Press
A Division of Microsoft Corporation
One Microsoft Way
Redmond, Washington 98052-6399
Copyright © 2010 by Dino Esposito
All rights reserved. No part of the contents of this book may be reproduced or transmitted in any form or by any means
without the written permission of the publisher.
Library of Congress Control Number: 2010925900
Printed and bound in the United States of America.
1 2 3 4 5 6 7 8 9 WCT 5 4 3 2 1 0
Distributed in Canada by H.B. Fenn and Company Ltd.
A CIP catalogue record for this book is available from the British Library.
Microsoft Press books are available through booksellers and distributors worldwide. For further information about
international editions, contact your local Microsoft Corporation office or contact Microsoft Press International directly at
fax (425) 936-7329. Visit our Web site at www.microsoft.com/mspress. Send comments to
Microsoft, Microsoft Press, ActiveX, Excel, IntelliSense, Internet Explorer, MS, MSDN, SharePoint, Silverlight, SQL
Server, Visual Basic, Visual C#, Visual Studio, Win32, Windows, Windows Server, and Windows Vista. Other product
and company names mentioned herein may be the trademarks of their respective owners.
The example companies, organizations, products, domain names, e-mail addresses, logos, people, places, and events depicted
herein are fictitious. No association with any real company, organization, product, domain name, e-mail address, logo,
person, place, or event is intended or should be inferred.
This book expresses the author’s views and opinions. The information contained in this book is provided without any
express, statutory, or implied warranties. Neither the authors, Microsoft Corporation, nor its resellers, or distributors will
be held liable for any damages caused or alleged to be caused either directly or indirectly by this book.
Acquisitions Editor: Ben Ryan
Developmental Editor: Lynn Finnel
Project Editors: Lynn Finnel and Carol Vu
Editorial Production: Ashley Schneider, S4Carlisle Publishing Services
Technical Reviewer: Kenn Scribner; Technical Review services provided by Content Master, a member


of CM Group, Ltd
Cover: Tom Draper Design
Body Part No. X16-88503
To Silvia, Francesco, and Michela, who wait for me and keep me busy.
But I’m happy only when I’m busy.
—Dino

v
Contents at a Glance
Part I The Programming Paradigm
1 Goals of ASP.NET MVC and Motivation
for Its Development 3
2 The Runtime Environment 37
3 The MVC Pattern and Beyond 81
Part II The Core of ASP.NET MVC
4 Inside Controllers 123
5 Inside Views 211
6 Inside Models 277
Part III Programming Features
7 Data Entry in ASP.NET MVC 317
8 The ASP.NET MVC Infrastructure 355
9 AJAX Capabilities 401
10 Testability and Unit Testing 435
11 Customizing ASP.NET MVC 477
vii
Table of Contents
Acknowledgments xiii
Introduction xv
Part I The Programming Paradigm

1 Goals of ASP.NET MVC and Motivation
for Its Development 3
The Deep Impact of ASP.NET 5
Productivity Is King . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
The Web Forms Model 9
The “Page Controller” Pattern 11
The ASP.NET Age of Reason 16
ASP.NET’s Signs of Aging 16
The Turning Point 20
ASP.NET MVC at a Glance 26
ASP.NET MVC Highlights 26
Web Forms vs. ASP.NET MVC 30
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35
2 The Runtime Environment 37
The ASP.NET Runtime Machinery 37
ASP.NET and the IIS Web Server 38
Life Cycle of an ASP.NET Request 44
What’s an HTTP Handler, Anyway? 51
What’s an HTTP Module, Anyway? 57
URL Routing 61
The ASP.NET MVC Run-Time Shell 67
The Big Picture 68
Processing an ASP.NET MVC Request 75
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80
Microsoft is interested in hearing your feedback so we can continually improve our books and learning
resources for you. To participate in a brief online survey, please visit:
www.microsoft.com/learning/booksurvey/
What do you think of this book? We want to hear from you!
viii Table of Contents
3 The MVC Pattern and Beyond 81

The Original MVC Pattern 82
MVC Interaction Model 82
The Original Idea 83
Presenting the Actors 84
Limitations of the MVC Pattern 89
The Model2 Pattern 90
MVC and the Web 90
Model2 and ASP.NET MVC 93
Presentation-Oriented Variations of MVC 98
The MVP Pattern 98
Presentation Model Pattern (Also Known as MVVM) 103
The ASP.NET MVC Project Template 107
Peculiarities of an ASP.NET MVC Project 108
ASP.NET MVC Special Folders 113
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
Part II The Core of ASP.NET MVC
4 Inside Controllers 123
The Role of Controllers and the Motivation for Using Them 123
Beyond the Code-Behind Approach 124
Introducing Controllers 128
Mechanics of Controllers in ASP.NET MVC 132
Anatomy of an ASP.NET MVC Controller 135
Inside the Structure of a Controller 135
Behavior of a Controller 144
Attributes of Controllers and Action Methods 156
Writing a Controller 167
Design of a Controller Class 167
Should You Use Your Own Base Class? 176
Special Capabilities 183
Grouping Controllers 184

Asynchronous Controllers 187
Render Actions 195
Controllers and Testability 199
Making Controllers Easy to Test 199
Writing Unit Tests 204
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209
Table of Contents ix
5 Inside Views 211
Views and Controllers 212
From Controllers to Views 212
Building the Response for the Browser 213
Anatomy of an ASP.NET MVC View 215
Selecting the View 215
Creating the View 220
The Default View Engine 222
The Web Forms View Engine 226
Writing a View 233
The View’s Template 235
Filling Up the View 241
HTML Helpers 252
Templated HTML Helpers 257
Datagrids and Paged Views 261
Testing a View 273
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
6 Inside Models 277
What’s the Model, Anyway? 278
How Many Types of Models Do You Know? 278
The Models Folder 282
Domain Model and View-Model 286
Business Object Modeling 286

Adding Validation Logic to the Model 291
Data for the View 299
Model Binding 305
The Model Binder in Action 306
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 313
Part III Programming Features
7 Data Entry in ASP.NET MVC 317
The Select-Edit-Save Pattern 318
Presenting Data 318
Editing Data 320
Saving Data 324
Data Validation 326
Validation on the Server Side 326
x Table of Contents
Giving Feedback to the User 334
Data Annotations and Validators 342
Client-Side Validation 351
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 354
8 The ASP.NET MVC Infrastructure 355
Routing 356
Dealing with Routes 356
Keeping an Eye on SEO 362
Error Handling 366
Foundations of ASP.NET Error Handling 366
Dealing with Missing Content 371
Localization 374
Making Resources Localizable 374
Dealing with Resources in ASP.NET MVC 376
Dependency Injection 382
Dependency Inversion in Action 383

A Brief Tour of Unity 391
Creating a Global Container 395
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 399
9 AJAX Capabilities 401
AJAX in ASP.NET 401
Partial Rendering 402
Direct Scripting 405
AJAX in ASP.NET MVC 408
The JavaScript API 408
The Controller Façade 413
AJAX Helpers in ASP.NET MVC 420
Partial Rendering in ASP.NET MVC 428
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 432
10 Testability and Unit Testing 435
Testability and Design 436
Design for Testability 436
Loosen Up Your Design 438
Basics of Unit Testing 443
Working with a Test Harness . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 443
Aspects of Testing 447
Table of Contents xi
Unit Testing in ASP.NET MVC 454
Testing Controller Actions 454
Injecting Mocks and Fakes 458
Mocking the HTTP Context 463
More Specific Tests 471
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 475
11 Customizing ASP.NET MVC 477
The Controller Factory 477
ASP.NET MVC Request Processing 478

Extending the Default Controller Factory 480
Invoking Actions 487
Action Filters 496
Gallery of Action Filters 496
Loading Action Filters Dynamically 505
Action Selectors 509
Action Results and Rendering 512
Processing the Result of the Action 512
Custom ActionResult Objects 514
View Engines 521
HTML Helpers 529
Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 538
Appendix: ReSharper and the Power of Tools 539
IntelliSense Extensions 539
Choose the Right View Name with IntelliSense Tips 540
Action Links and URLs 541
User Controls 542
Static Analysis to Detect Missing Views and Actions 542
Coding Assistants 543
Creating Views by Usage 543
Navigation 545
Controller and View Navigation 545
Locating Symbols 547
Navigating Inside Master and Content Pages 547
Refactoring for ASP.NET MVC 548
Conclusion 549
Index 551
Microsoft is interested in hearing your feedback so we can continually improve our books and learning
resources for you. To participate in a brief online survey, please visit:
www.microsoft.com/learning/booksurvey/

What do you think of this book? We want to hear from you!
xiii
Acknowledgments
The man who doesn’t read good books has no advantage over the man who can’t
read them.
—Mark Twain
We started discussing this book around the release of ASP.NET MVC 1.0, in the late spring of
2009. It was not exactly an ideal time for making plans, even though business had to go on in
spite of the world financial crisis and severe downturn in the economy. Now that the book is
finished, we seem to live in slightly better times, and we all sincerely hope that the worst of it
is behind us. However, as I look at this book project now that it’s finished, I realize I’m deeply
missing one special person—Lynn Finnel.
Lynn was laid off in the middle of the project as a result of one of the many restructurings
that a lot of companies went through in the past year. Lynn and I have done so many
books together, and we always shared a mutual high level of satisfaction with the outcome.
Not sending chapters and reviews to Lynn any more was a big change in this part of my
professional life. And, who knows, one day I might have Lynn, at the height of her new career
as a physical therapist, just take care of my poor back, stressed by its unnatural posture and
too many hours of tennis.
Changing the project editor in the middle of a book project can sometimes be a tough
experience, but as arranged by Carol Vu the transition was seamless. Despite the difficulties
in replacing an editor of Lynn’s caliber, I really didn’t notice any difference.
In the past few months, Ben Ryan got a bunch of e-mails from me asking, with different
tones, always the same question: “Are you still there?” Yes, fortunately, he’s still there with
prompt and insightful suggestions. Cheap and valuable—only two cents each! But I’ve never
valued any advice more than Ben’s two-cent propositions.
And, fortunately, Kenn Scribner is still part of the team and a rock-solid pillar. The degree to
which Kenn can be helpful is just beyond human imagination. Now Kenn, let me challenge
you: I wrote this same sentence about you in another book. Which one? Hey, you have only
a few days to answer as another project is in sight! :)

Many editors say that my written English is more than acceptable for it not being my first
language. Readers don’t actually know much about my (real) English because Roger LeBlanc
has a pass on every thought that I happen to put down in words. I would like a wireless
version of Roger that could intercept my thoughts at the source and fix them in correct
English right away.
xiv Acknowledgments
I owe you all the usual, but heart-felt, monumental “Thank You” for being so kind, patient,
and accurate. (Don’t worry, Roger will have fixed this too.)
Like millions of other Italian students, I spent many hours of my teenage years trying to
catch the spirit of The Divine Comedy. As you may know, the whole poem develops around
a journey that Dante undertakes through the three realms of the dead, guided by the Roman
poet Virgilio. With due distance, I similarly spent many hours of my past months trying to
catch and express the gist of ASP.NET MVC. I began a journey through controllers, views,
models, and filters, guided by a top-notch developer, trainer, and friend—Hadi Hariri.
At times during the project, I searched for advice on a few specific architectural aspects of
ASP.NET MVC and found that
1. The number of matching responses was surprisingly low.
2. And the first significant post reported was from Hadi.
This combination of results happened only a couple of times, but a couple of times is a huge
quantity given the very specific questions I was trying to find out more.
After advocating ReSharper for many years, Hadi now works for JetBrains and reinforced
the strongly positive feeling I always had for the product. Of course, he helped me a lot with
the appendix at the end of the book.
Loyal readers of my books may know about my (insane) passion for tennis. My wife, Silvia,
asked me once, “OK, you like tennis so much, but is there any chance that you can make some
money from it?” I never dared ask whether she meant “make money playing and winning
tournaments” or “make money through software applied to tennis.” To be on the safe side,
I covered both possibilities and decided to train and play a lot more, while spending many
hours helping out Giorgio Garcia and the entire team at Crionet and e-tennis.tv to serve
better services to tennis tournaments and their related fans.

Finally, I must mention my kids, Francesco (12) and Michela (9). In different ways, they seem
to feel comfortable on stage, be it on Wimbledon’s Centre Court with Roger Federer in the
background or in a nice theater in Rome.
Till the next one!
Dino Esposito

xv
Introduction
Get your facts first, and then you can distort them as much as you please.
—Mark Twain
In the spring of 2006, I had the privilege of taking a very early look at what would eventually
become ASP.NET MVC. Scott Guthrie of Microsoft arranged a personal demo just for me
backstage at the DevConnections conference in balmy Nice, France. At the time, I had just
started playing with ASP.NET Web Forms and the Model-View-Presenter (MVP) pattern.
I expected to see the usual great set of designers to automatically define models, controllers,
and views. Instead, I was surprised to see a brand-new application model being worked out
on top of the same ASP.NET runtime. (Note that what I saw at that time was at best a distant
relative to what you know today as ASP.NET MVC, but the key facts were already visible.)
Not that getting rid of the postback model looked like a bad thing to me, but frankly the
idea of changing the programming model quite significantly didn’t impress me that much.
The combination of ASP.NET Web Forms and MVP seemed to me a more natural and less
disruptive way to achieve separation of concerns and overall better quality code. Scott
pointed me to a couple of team members that I pinged a few times during the summer
for more information and newer builds. But nothing happened. Instead, in the summer of
2006 all the excitement being generated was for the upcoming ASP.NET AJAX Extensions
(remember Atlas?). Overwhelmed by the AJAX bandwagon, I gravitated to this clear
sentiment: that funky ASP.NET MVC thing was just a proof of concept, a good-for-fun project.
So I removed it from my mind.
In October 2007, I was in Malaga, Spain, to make a presentation to a local user group. During
a break, my friend Hadi Hariri asked my opinion about the just-released, first preview of

ASP.NET MVC.
ASP.NET what?
I had a look at the bits, and a few weeks later I even wrote one of the very first articles about
ASP.NET MVC for the DotNetSlackers Web site. The article is still there (and mostly valid) at

.aspx. The taste of ASP.NET MVC was bittersweet for me. Overall, ASP.NET MVC seemed like
an entire step backwards and I couldn’t see the point of it. And I asked the same question so
many times:
When is this going to be really (and tangibly) better than ASP.NET Web Forms?
This is the fundamental question. And it is still largely unanswered, to the point that I suspect
that it can’t really have an answer.
xvi Introduction
Although it’s based on the same runtime environment, ASP.NET MVC is significantly different
from ASP.NET Web Forms. It supports a radically different pattern—MVC (actually the special
flavor of MVC known as Model2) rather than a pure Page Controller—and was designed with
a radically different set of goals—testability, extensibility, and closeness-to-the-metal of both
the Web and ASP.NET runtime.
It doesn’t matter what kind of software professional you are, when it comes to choosing the
platform for a new .NET Web application you feel like you are at a crossroads. You know you
have to choose, and you look around for guidance. You see pros and cons on both sides,
and you can hardly see—clearly and tangibly—what’s the right way to go. For this reason,
the core question—should we use ASP.NET Web Forms or ASP.NET MVC—often ends up
being an endless and pointless religious discussion where all parties push their own vision
and scream louder with the gathering force of their conviction.
In the end, the correct answer is that it depends. In the end, the choice is really like Microsoft
describes it: car vs. motorcycle or automatic vs. manual.
This leads to a new and largely unspoken question: Did we really need a second option?
Wouldn’t it have been better for us if Microsoft detected the signs of age of Web Forms
and worked as hard as they worked on ASP.NET MVC to improve that, sticking to just one
framework?

Aren’t two options always better than one? Sure, but two options imply a choice. And
a choice implies information, education, and responsibility. Here’s where this book
hopefully fits in.
ASP.NET MVC and Web Forms
Until late 2008, I was happy enough with Web Forms. I did recognize its weak points and was
able to work around them nicely with discipline and systematic application of design
principles. In the beginning, ASP.NET MVC was enthusiastically received by a relatively small
segment of the community, but one that was screaming loudly and posting a lot. Even
though I’ve never been a member of the ALT.NET community, I’m still constantly keeping
an eye out for any better ways of doing my tasks. So I started to explore the ASP.NET MVC
architecture and tried to understand its potential, while constantly trying to envision concrete
business scenarios in which to employ it. I did this for about a year.
What did I learn?
Technically speaking, ASP.NET MVC is far superior to Web Forms. This is because it’s
newer and was designed around an alternate and more modern set of principles and
patterns. Is this sufficient reason for you to switch to it? In my opinion, it isn’t. ASP.NET
MVC is an excellent choice from the perspective of developers, but that fact alone doesn’t
Introduction xvii
automatically translate into a tangible benefit for the customer and the project. Moreover,
ASP.NET MVC is much less forgiving than Web Forms and requires training, or at least
self-training.
In 10 years of using Web Forms, I’ve seen many professionals with limited programming skills
produce effective Web front ends using data-bound controls and a bit of Microsoft Visual
Basic. This will not happen with ASP.NET MVC. Worse yet, if you start writing ASP.NET MVC
code taking the learn-as-you-go approach that worked for many with Web Forms, you will
surely cook up great examples of much hated spaghetti code.
So learning ASP.NET MVC makes you a better developer, but it has a cost. Who’s supposed
to pay for that? Your customer? Your company? You, yourself? How would you justify to
a project manager the extra training costs for just using ASP.NET MVC? You can try, but the
natural objection is this: “OK, but where’s my return? Can’t we take this project home by

simply using Web Forms, which we already know through and through?”
In the end, picking ASP.NET MVC over Web Forms is a matter of preference and attitude,
or it’s a matter of dealing with some nonfunctional requirements. In the first case, you don’t
have extra costs because it can be assumed you know your stuff very well. The second case,
instead, introduces the only scenario I can think of where ASP.NET MVC is a clear winner.
How can you fulfill requirements such as strict accessibility, adherence to Web standards,
XHTML, theme-ability, cross-browser experience, and rich AJAX capabilities?
These requirements lead to the necessity of exercising strict control over the markup emitted
for each page. This is an area where ASP.NET MVC is incomparably better than Web Forms,
even when you take into consideration Microsoft’s latest improvements to the ASP.NET 4
framework and your own programming self-discipline.
Every other argument being presented as a plus of ASP.NET MVC—such as testability,
separation of concerns, extensibility, and the like—is just a plus of the framework, not
a breakthrough for the project. By the way, even though in the .NET space we seem to have
discovered testability only a few years ago, it has been listed as a fundamental attribute of
software in the ISO/IEC 9126 paper since 1991. (For more information, have a look at
/>Who Is This Book For?
As explained in great detail in Chapter 1, “Goal of ASP.NET MVC and Motivation for Its
Development,” ASP.NET Web Forms is showing the signs of age. And ASP.NET MVC is an
excellent (although still incomplete) replacement. My guess—my humble, two-cent guess—is
that in a couple of years (and in a couple of versions) ASP.NET MVC will offer the same level
of productivity as Web Forms—either because of framework enhancements or because of
xviii Introduction
even more powerful tooling. At that point, you will have two options that are equivalent
functionally and in terms of productivity. But one of them (ASP.NET MVC) can help you write
better code, faster. This may not be the case today with ASP.NET MVC 2, but it likely will be
the case with ASP.NET MVC 3 or 4.
I don’t think that ASP.NET Web Forms will be dismissed very soon. For example, rumors
suggest that ASP.NET Web Forms will move decidedly toward increasing testability in
version 5 through the introduction of some MVP support. We’ll see, but as I see things

ASP.NET MVC is and will remain far superior technically.
Although pushing a team to use ASP.NET MVC today on a project might be an arguable
choice, pushing it within a software company isn’t an arguable choice at all. Having a deep
understanding of ASP.NET MVC makes you a better developer. ASP.NET MVC is easy to pick up
for junior developers who are just out of school, even though it could be harder for experienced
Web Forms developers to learn. This book assumes you have knowledge of Web Forms
programming as it explains how ASP.NET MVC works and how to use it effectively.
My experience shows that too many Web Forms developers built their expertise by trial
and error. ASP.NET MVC requires a sort of reset, and you know that after you reboot your
machine it normally runs faster. But this personal reboot may take a bit of effort. Start
today with ASP.NET MVC, even in parallel with current Web Forms projects. You’ll see the
difference, understand the basic facts of Web development, and soon be ready for writing
better code with both Web Forms and ASP.NET MVC.
Companion Content
This book features a companion Web site that makes available to you all the code used in the
book. This code is organized by chapter, and you can download it from the companion site at
this address: />Hardware and Software Requirements
You’ll need the following hardware and software to work with the companion content
included with this book:
n
Microsoft Windows Vista Home Premium Edition, Windows Vista Business Edition,
or Windows Vista Ultimate Edition, Microsoft Windows 7 Home Premium Edition,
Windows 7 Business Edition, or Windows 7 Ultimate Edition, Windows Server 2008, SP1.
n
Microsoft Visual Studio 2008 Standard Edition, Visual Studio 2008 Enterprise Edition,
or Microsoft Visual C# 2008 Express Edition and Microsoft Visual Web Developer 2008
Express Edition, Visual Studio 2010 Professional Edition, Visual Studio 2010 Premium
Edition, Visual Studio 2010 Ultimate Edition.
Introduction xix
n

Microsoft SQL Server 2008 Express Edition, Service Pack 1.
n
1.6 GHz Pentium III+ processor, or faster.
n
1 GB of available, physical RAM.
n
Video (800 × 600 or higher resolution) monitor with at least 256 colors.
n
CD-ROM or DVD-ROM drive.
n
Microsoft mouse or compatible pointing device.
Support for This Book
Every effort has been made to ensure the accuracy of this book. As corrections or
changes are collected, they will be added to a Microsoft Knowledge Base article accessible
via the Microsoft Help and Support site. Microsoft Press provides support for books,
including instructions for finding Knowledge Base articles, at the following Web site:
/>If you have questions regarding the book that are not answered by visiting the site
above or viewing a Knowledge Base article, send them to Microsoft Press via e-mail to

Please note that Microsoft software product support is not offered through these addresses.
We Want to Hear from You
We welcome your feedback about this book. Please share your comments and ideas via the
following short survey: />Your participation will help Microsoft Press create books that better meet your needs
and your standards.
Note We hope that you will give us detailed feedback via our survey. If you have questions
about our publishing program, upcoming titles, or Microsoft Press in general, we encourage you
to interact with us via Twitter at For support issues, use only
the e-mail address shown above.

1

Part I
The Programming Paradigm
3
Chapter 1
Goals of ASP.NET MVC and
Motivation for Its Development
You affect the world by what you browse.
—Tim Berners-Lee
The open era of the World Wide Web (WWW) began on April 30, 1993. That day, the
European Organization for Nuclear Research (CERN, from the French original name of Conseil
Européen pour la Recherche Nucléaire) announced publicly that the World Wide Web would
be free for anyone to browse and build within.
As a Web professional, you should keep this date in mind, carefully track it in your calendar
and, perhaps, celebrate it regularly with friends and family. It is a significant day in history.
After all, it’s the date on which your profession was officially born. Without this date in
history, you might have found yourself a car mechanic or store salesperson!
As Tim Berners-Lee—the inventor of the World Wide Web—noted once, the development of
the Web was very quick compared to other media and mass devices such as the telephone
or TV. A number of ancillary factors contributed to the rapid growth of the WWW. One
was certainly the decision, adopted only a few weeks before the CERN announcement,
by the University of Minnesota to charge a fee for use of its Gopher server. At the time,
Gopher—a TCP/IP layer for retrieving documents over the Internet—was an even better
established and more credible alternative to the World Wide Web. The fee announced by the
University of Minnesota was only for the use of one particular server, but people saw in it the
threat of an incoming charge to be imposed on any Gopher server worldwide.
That’s just one example of an early catalyst to the growth of the WWW. You’ve lived and
personally experienced the rest of the story.
By the end of the 1990s, Gopher was in full stagnation while the WWW was expanding and,
among other things, fueling the notorious Internet bubble. (If you’re curious about Gopher,

you can dig further into the topic by visiting the reference on Wikipedia at the following
a d d r e s s : />The first significant Web sites and applications appeared shortly after CERN waived any
copyrights on the WWW. In general terms, a Web application is a kind of client/server
application that consists of a set of individually addressable pages. Pages form the user
4 Part I The Programming Paradigm
interface of the application and are accessed via a general-purpose client application—the
Web browser. Pages work over the network whether it is the Internet or an intranet.
What is a Web page? How is a Web page coded?
The answers to these questions are precisely what this book covers from the perspective
of ASP.NET MVC, which is a framework for building Web applications using the Microsoft
ASP.NET platform. ASP.NET MVC (for Model View Controller) marks a significant change in
how developers code Web pages within the ASP.NET platform.
Abstractly speaking, a Web page can be seen as a dual container where a public interface is
backed by a number of technologies on a variety of hardware/software platforms. Publicly,
a Web page produces a standard markup mix made of HTML, cascading style sheets (CSS),
and JavaScript that Web browsers know how to render. Internally, a Web page can employ
a number of technologies, frameworks, languages, and patterns to process a Web request to
an acceptable markup mix.
Microsoft scored a remarkable victory in the Web industry with the introduction of the
ASP.NET platform back in 2001. ASP.NET opened the doors of Web development to a huge
number of professionals and contributed to changing the development model of Web
applications. ASP.NET wasn’t alone in producing this effort. ASP.NET followed up the progress
made by at least a couple of earlier technologies: classic Active Server Pages (ASP) and Java
Server Pages (JSP).
In its early years, the Web pushed an unusual programming model and a set of programming
tools and languages that were unknown or unfamiliar to the majority of programmers. Anybody
who tried to build even a trivial Web site in the 1990s had to come to grips with the HTML
syntax and at least the simplest JavaScript commands and objects. The public interface of Web
pages—the aforementioned markup mix—had to be written manually in the past decade.
And this created a sort of trench separating die-hard C/C++ programmers from freaky Web

developers.
Whereas classic ASP introduced the concept of dynamic content generation and laid the
groundwork for rapid application development (RAD) tools, JSP explored a more structured
approach to Web development based on the reassessment of some popular (and effective)
design patterns.
Classic ASP was a blast to work with because developers really liked the idea of designing
Web pages as HTML-based templates interspersed with some code blocks to be interpreted
and executed at run time and generating dynamic content on the fly. However, there’s
a strong, underlying assumption in this model.
Chapter 1 Goals of ASP.NET MVC and Motivation for Its Development 5
Any Web requests that come along are processed to generate an HTML page. All server
efforts to process the request are aimed at getting an HTML page, from the opening
<html> tag to the closing </html> tag. Any code and processing required along the way
are overshadowed by the necessity of producing detailed HTML. The link between the Web
request and some server-side operation is surely not lost, but it doesn’t always show up
clearly at the developer level.
For years, this remained the major difference between classic ASP (and, later, ASP.NET) and
JSP. This gap is covered today with the release of an alternative programming model for the
ASP.NET platform. Welcome, ASP.NET MVC!
Note You might have noticed that I didn’t mention Personal Home Page (PHP) language when
I listed some of the technologies that influenced Web development models. When it comes to
Web development technologies, PHP can’t just be ignored.
According to Netcraft’s January 2010 Web server survey (which you can find at http://news
.netcraft.com/archives/2010/01/07/january_2010_web_server_survey.html), Apache is firmly the
market leader serving around 50 percent of monitored sites. And because Apache is part of
the open-source LAMP (Linux + Apache + MySQL + PHP) stack—with Linux as the operating
system, Apache as the Web server, MySQL as the database server, and PHP (or Python or Perl)
as the programming language—you can easily conclude that PHP is an extremely popular Web
development framework. PHP and ASP.NET together have the lion’s share of the development
market.

However, PHP and ASP.NET developed along independent paths and thus have quite different
characteristics. ASP.NET was devised to be the successor of classic ASP; in the newer flavor of
ASP.NET MVC, some of the ideas originally developed for JSP have been reworked. That’s why
you didn’t find PHP mentioned earlier.
The Deep Impact of ASP.NET
Classic ASP had two main merits. First, it made dynamic HTML generation really easy for
many developers. Second, it was one of the first programming environments to host the logic
of Web applications within the Web server with a subsequent marked performance gain.
Based on script code and interpreted by a runtime engine, ASP pages were upgraded to the
rank of compiled code with the advent of the .NET platform. Totally superseded by ASP.NET,
classic ASP is today a dead end and survives only in legacy Web sites.
ASP.NET pages are based on compiled code written using first-class programming languages
such as Microsoft C# and Visual Basic. What was easy and effective to do with classic ASP
turned out to be even easier and smoother with ASP.NET.

×