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

ASP net MVC in action

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 (12.85 MB, 391 trang )

MANNING
Jeffrey Palermo
Ben Scheirman
Jimmy Bogard
FOREWORD BY PHIL HAACK
IN ACTION
ASP.NET MVC in Action
Licensed to Gayle M. Noll <>
Download at Boykma.Com

Licensed to Gayle M. Noll <>
Download at Boykma.Com
ASP.NET MVC
in Action
WITH MVCCONTRIB, NHIBERNATE, AND MORE
JEFFREY PALERMO
BEN SCHEIRMAN
JIMMY BOGARD
MANNING
Greenwich
(74° w. long.)
Licensed to Gayle M. Noll <>
Download at Boykma.Com
For online information and ordering of this and other Manning books, please visit
www.manning.com. The publisher offers discounts on this book when ordered in quantity.
For more information, please contact
Special Sales Department
Manning Publications Co.
Sound View Court 3B fax: (609) 877-8256
Greenwich, CT 06830 email:
©2010 by Manning Publications Co. All rights reserved.


No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in
any form or by means electronic, mechanical, photocopying, or otherwise, without prior written
permission of the publisher.
Many of the designations used by manufacturers and sellers to distinguish their products are
claimed as trademarks. Where those designations appear in the book, and Manning
Publications was aware of a trademark claim, the designations have been printed in initial caps
or all caps.
Recognizing the importance of preserving what has been written, it is Manning’s policy to have
the books we publish printed on acid-free paper, and we exert our best efforts to that end.
Recognizing also our responsibility to conserve the resources of our planet, Manning books are
printed on paper that is at least 15% recycled and processed without the use of elemental chlorine.
Development Editor: Tom Cirtin
Copyeditor: Betsey Henkels
Manning Publications Co. Proofreader: Elizabeth Martin
Sound View Court 3B Typesetter: Gordan Salinovic
Greenwich, CT 06830 Cover designer: Leslie Haimes
ISBN 978-1-933988-62-7
Printed in the United States of America
1 2 3 4 5 6 7 8 9 10 – MAL – 14 13 12 11 10 09
Licensed to Gayle M. Noll <>
Download at Boykma.Com
v
brief contents
1 ■ Getting started with the ASP.NET MVC Framework 1
2
■ The model in depth 24
3
■ The controller in depth 44
4
■ The view in depth 65

5
■ Routing 91
6
■ Customizing and extending the ASP.NET MVC Framework 119
7
■ Scaling the architecture for complex sites 152
8
■ Leveraging existing ASP.NET features 174
9
■ AJAX in ASP.NET MVC 195
10
■ Hosting and deployment 216
11
■ Exploring MonoRail and Ruby on Rails 238
12
■ Best practices 270
13
■ Recipes 312
Licensed to Gayle M. Noll <>
Download at Boykma.Com
Licensed to Gayle M. Noll <>
Download at Boykma.Com
vii
contents
foreword xiii
preface
xv
acknowledgments
xviii
about this book

xxi
about the authors
xxvi
about the cover illustration
xxviii
1
Getting started with the ASP.NET MVC Framework 1
1.1 Picking apart the default application 3
Creating the project 4

Your first routes 7

Running with the
starter project
9
1.2 Your first ASP.NET MVC controller from scratch 14
1.3 Our first view 16
1.4 Ensuring the application is maintainable 18
1.5 Testing controller classes 20
1.6 Summary 22
2
The model in depth 24
2.1 Understanding the basics of domain-driven design 25
2.2 Domain model for this book 26
Key entities and value objects 26

Aggregates 27

Persistence
for the domain model

29
Licensed to Gayle M. Noll <>
Download at Boykma.Com
CONTENTS
viii
2.3 Presentation model 31
Presentation model responsibilities 31

Projecting from the
domain model
33
2.4 Working with the model 34
Crafting the route 35

Crafting the controller action 35

Test-
driving the feature
36

Finishing the view 39
2.5 Summary 42
3
The controller in depth 44
3.1 The controller action 45
3.2 Simple controllers do not need a view 47
3.3 Testing controllers 50
Testing the RedirectController 50

Making dependencies

explicit
52

Using test doubles, such as stubs and
mocks
53

Elements of a good controller unit test 55
3.4 Simple actions and views 56
3.5 Working with form values 57
3.6 Processing querystring parameters 58
3.7 Binding more complex objects in action parameters 59
3.8 Options for passing ViewData 61
3.9 Filters 62
3.10 Summary 64
4
The view in depth 65
4.1 How ASP.NET MVC views differ from Web Forms 66
4.2 Folder structure and view basics 67
4.3 Overview of view basics 69
Examining the IViewEngine abstraction 70

Understanding
master pages in the ASP.NET MVC Framework
71

Using
ViewData to send objects to a view
73


Partial views can help
decompose a complex screen
76
4.4 Leveraging the view to create dynamic screens 79
Rendering forms with view helpers and data binding 79

Posting
HTML forms back to the server
84

Validation and error
reporting
85

Extending HtmlHelper 88
4.5 Summary 90
Licensed to Gayle M. Noll <>
Download at Boykma.Com
CONTENTS
ix
5
Routing 91
5.1 What are routes? 92
What’s that curl command? 92

Taking back control of the URL
with routing
94
5.2 Designing a URL schema 95
Make simple, clean URLs 95


Make hackable
URLs
96

Allow URL parameters to clash 96

Keep URLs
short
97

Avoid exposing database IDs wherever possible 97

Consider adding unnecessary information 98
5.3 Implementing routes in ASP.NET MVC 99
URL schema for an online store 102

Adding a custom static
route
103

Adding a custom dynamic route 103

Catch-all
routes
105
5.4 Using the routing system to generate URLs 107
5.5 Creating routes for Code Camp Server 108
5.6 Testing route behavior 111
5.7 Using routing with existing ASP.NET projects 115

5.8 Summary 117
6
Customizing and extending the ASP.NET MVC Framework 119
6.1 Extending URL routing 120
6.2 Creating your own ControllerFactory 125
The ControllerFactory implementation 126

Leveraging IoC for
your controllers
130
6.3 Extending the controller 134
Creating a FormattableController 135

Working with action
filters
138
6.4 Creating a custom view engine 141
6.5 Customizing Visual Studio for ASP.NET MVC 145
Creating custom T4 templates 145

Adding a custom test project
template to the new project wizard
148
6.6 Summary 150
7
Scaling the architecture for complex sites 152
7.1 Taming large controller actions 153
7.2 Whipping views into shape 156
Using and creating view helpers 156


Creating
partials
159

Creating components 163
Licensed to Gayle M. Noll <>
Download at Boykma.Com
CONTENTS
x
7.3 Using action filters to load common data 165
7.4 Organizing controllers into areas 167
Capturing the area for a request 168

Creating a view engine
with support for areas
168

Tying it all together 171
7.5 Summary 172
8
Leveraging existing ASP.NET features 174
8.1 ASP.NET server controls 175
The TextBox 175

Other common controls 176

The
GridView
178


Where do I get the good stuff? 179
8.2 State management 179
Caching 179

Session state 183

Cookies 184

Request
storage
184
8.3 Tracing and debugging 185
TraceContext 186

Health monitoring 186
8.4 Implementing personalization and localization 187
Leveraging ASP.NET personalization 187

Leveraging
ASP.NET localization
188
8.5 Implementing ASP.NET site maps 192
8.6 Summary 194
9
AJAX in ASP.NET MVC 195
9.1 Diving into AJAX with an example 196
9.2 AJAX with ASP.NET Web Forms 198
9.3 AJAX in ASP.NET MVC 200
Hijaxing Code Camp Server 201


AJAX with JSON 207

Adding alternate view formats to the controller 208

Consuming
a JSON action from the view
210

AJAX helpers 213
9.4 Summary 214
10
Hosting and deployment 216
10.1 Deployment scenarios 217
10.2 XCOPY deployment 218
10.3 Deploying to IIS 7 219
10.4 Deploying to IIS 6 and earlier 223
Configuring routes to use the .aspx extension 224

Configuring
routes to use a custom extension
225

Using wildcard mapping
with selective disabling
226

Using URL rewriting 229
Licensed to Gayle M. Noll <>
Download at Boykma.Com
CONTENTS

xi
10.5 Automating deployments 232
Employing continuous integration 232

Enabling push-button XCOPY
deployments
233

Managing environment configurations 234
10.6 Summary 237
11
Exploring MonoRail and Ruby on Rails 238
11.1 MonoRail 239
Feature overview 239

ActiveRecord and Windsor 248

MonoRail and Castle features available in ASP.NET MVC 255
11.2 Ruby on Rails 255
Convention over configuration and “the Rails way” 256

Active
Record
260

ActionPack 264
11.3 Summary 269
12
Best practices 270
12.1 Controllers 271

Layer Supertype 271

Filters 272

Smart binders 274

Hardcoded strings 279

Separated view models 280

Validation 281
12.2 Views 283
Strongly typed views 283

Fighting duplication 284

Embracing
expressions
286
12.3 Routes 289
Testing routes 289

Action naming 292
12.4 Testing 294
Controller unit tests 295

Model binder unit tests 298

Action filter
unit tests

301

Testing the last mile with UI tests 303
12.5 Summary 311
13
Recipes 312
13.1 jQuery autocomplete text box 312
13.2 Automatic client-side validation 318
13.3 Data access with NHibernate 325
Functional overview of reference implementation 326

Application architecture overview 327

Domain model—the
application core
328

NHibernate configuration—infrastructure
of the application
330

UI leverages domain model 338

Pulling it together 341

Wrapping up data access with
NHibernate
344
Licensed to Gayle M. Noll <>
Download at Boykma.Com

CONTENTS
xii
13.4 Designing views with the Spark view engine 345
Installing and configuring Spark 345

Simple Spark view
example
347
13.5 Summary 351
index 353
Licensed to Gayle M. Noll <>
Download at Boykma.Com
xiii
foreword
The final version of ASP.NET MVC 1.0 was released March 2009 during the Mix 09 con-
ference and nobody was caught by surprise with what was inside—and this is a good
thing. Before the debut of the final version, the product team had released multiple
public previews with full source code in an effort to raise the bar on openness and
community involvement for a Microsoft product.
Why would we do this?
Transparency and community involvement are noble goals, but they aren’t neces-
sarily the end goal of a project. What we’re really after is great product. I like to think
of
ASP.NET MVC as almost an experiment to demonstrate that transparency and com-
munity involvement were great means to achieving that goal.
After Preview 2 of
ASP.NET MVC was released, we received a lot of feedback from
developers that writing unit tests with
ASP.NET MVC was difficult. Jeffrey Palermo, the
lead author of

ASP.NET MVC in Action, was among the most vocal in providing feedback
during this time. We took this feedback and implemented a major API change by
introducing the concept of action results, which was a much better design than we
had before. Community involvement helped us build a better product.

ASP.NET MVC focuses on solid principles such as separation of concerns to provide
a framework that is extremely extensible and testable. While it’s possible to change the
source as you see fit, the framework is intended to be open for extension without need-
ing to change the source. Any part of the framework can be swapped with something
else of your choosing. Don’t like the view engine? Try Spark view engine. Don’t like the
way we instantiate controllers? Hook in your own dependency injection container.
Licensed to Gayle M. Noll <>
Download at Boykma.Com
FOREWORD
xiv
ASP.NET MVC also includes great tooling such as the Add View dialog, which uses
code generation to quickly create a view based on a model object. The best part is that
all the code generation features in
ASP.NET MVC rely on T4 templates and are thus
completely customizable.
With this book, Jeffrey will share all these features and more, as well as show how to
put them together to build a great application. I hope you enjoy the book and share
in his passion for building web applications. Keep in mind that this book is not only
an invitation to learn about
ASP.NET MVC, but also an invitation to join in the commu-
nity and influence the future of
ASP.NET MVC. Happy coding!
P
HIL HAACK
SENIOR PROGRAM MANAGER

ASP.NET MVC TEAM
MICROSOFT
Licensed to Gayle M. Noll <>
Download at Boykma.Com
xv
preface
My career started in the mid-nineties as one of the early web developers. Web as in
HTTP, that is. Netscape Navigator was helping to grow the number of households with
internet modems because it was more advanced than anything else at the time.
Netscape Navigator 3.0 (1996) and 3.04 (1997) helped households and businesses all
over the world open up the internet for common uses. There is no more common a
task than shopping! With the advent of ecommerce, the internet exploded with a cap-
italist gold run.
I started web development in the public sector where we leveraged the first threads
of social networking by allowing school district graduates to collaborate with former
classmates. I started my career on the Microsoft platform using
IDC (Internet Database
Connector) with
HTX (HTML Extension Template). Internet Information Services (IIS) 2.0
gave us fantastic flexibility using
ODBC data sources. This was my first use of the “code
nugget,” or <% %> delimiters.
IDC/HTX gave way to Active Server Pages (ASP), and I
can still recall following the changes as they broke–
ASP 2.0 to ASP 3.0 as well as the awe-
some
COM+ integration. I dabbled in CGI, Perl, Java, and C++, but stayed with the
Microsoft platform. Observing the Visual Basic explosion from the sidelines, I learned
the ropes with small utility apps.
Active Server Pages 3.0 saw the browser wars with Internet Explorer 4, released

with Windows 95, competing with Netscape for market share. Writing web applica-
tions that worked well with both browsers was difficult.
IE 5.0 opened the horizons for
intranet applications with proprietary web extensions like the
XML data island and
better scripting capabilities. Windows
XP shipped with IE 6, which effortlessly cap-
tured the majority of the web browser market.
ASP 3.0 put the programmer intimately
Licensed to Gayle M. Noll <>
Download at Boykma.Com
PREFACE
xvi
in touch with HTTP, HTML, and the GET and POST verbs. I remember pulling out
crude frameworks to handle multiple request paths from the same
ASP script.
At the same time
ASP 3.0 was enjoying widespread adoption, Struts was taking the
Java web application world by storm. Struts is probably the best known Java
MVC frame-
work, although today there are many popular frameworks for the
JVM. With ASP 3.0, I
was unaware of the lessons my Java counterparts had already learned, although I felt the
pain of myriad responsibilities lumped into a single
ASP script.
I adopted
ASP.NET 1.0 right out of the gate and converted some of my ASP 3.0 sites
to Web Forms. Remember when GridLayout was the default with
CSS absolute posi-
tioning everywhere? It was clear that Web Forms 1.0 was geared for

VB6 developers
coming over to .
NET and getting onto the web. The post-backs and button click han-
dlers were largely foreign to me, but my colleagues who were seasoned VB6ers felt
right at home.
ASP.NET 1.1 dropped the GridLayout and forced the developer to
understand
HTML and how flow layout works. Down-level rendering was great when
Internet Explorer was the “preferred” browser, and everything else was downlevel. That
paradigm started to break down as Firefox climbed in market share and demanded
standards-compliant markup.
I became an
ASP.NET expert and was a frequent blogger during the .NET 2.0 beta
cycle. I knew every feature and every breaking change from
ASP.NET 1.1 to 2.0, and
helped my team adopt 2.0. During the
ASP.NET 2.0 era, I started following Martin
Fowler and his Model-View-Presenter writings. I implemented that pattern to pull away
logic from the code-behind file, which had become bloated. Java developers, in 2005,
were enjoying a choice of several
MVC frameworks for the web. I, on the other hand, was
wrestling Web Forms into Model-View-Presenter and test-driven development submis-
sion. It was exhausting, but what was the alternative?
In 2006, with a job change, I jumped over to software management and smart client
development with WinForms. With the familiar clunkiness of the code-behind model,
and a development team to manage, I implemented the Model-View-Controller pattern
with the WinForm class as the view. It was a breath of fresh air. UI development was
seamless, and the controllers were a natural boundary from the domain model to the
UI. In 2007, I jumped back into web development and begrudgingly implemented
Model-View-Presenter with Web Forms again. In retrospect, I wish I had adopted Mono-

Rail, another Model-View-Controller framework for .
NET.
In February 2007, Scott Guthrie (ScottGu) created a prototype of what would
become the
ASP.NET MVC framework. He had heard from many customers about the
difficulties with Web Forms and how they needed a simpler, more flexible way to write
web applications. At the 2007
MVP Summit, Scott sought input from a small group of
Microsoft
MVPs. Darrell Norton, Scott Bellware, Jeremy Miller, and I validated the vision
of his prototype and gave initial input that would end up coded into the framework.
When Scott Guthrie presented, to an audience in Austin, Texas, a working proto-
type and vision for
ASP.NET MVC at the AltNetConf open spaces conference in Octo-
ber 2007, I knew instantly that this is what I’d wished for all along. As a long-time web
developer, I understood
HTTP and HTML, and this, I believe, is what ASP.NET 1.0
should have been. It would have been such a smooth transition from
ASP 3.0 to
Licensed to Gayle M. Noll <>
Download at Boykma.Com
PREFACE
xvii
ASP.NET MVC
. I can claim the first ASP.NET MVC application in production because I
convinced Scott to give me a copy of his prototype and revised my www.partywithpal-
ermo.com registration site, launching it in November 2007 on one of Rod Paddock’s
servers at DashPoint.
What Microsoft did with the
ASP.NET MVC release cycle was an unprecedented

project in the Developer Division. The project was released at least quarterly on the
CodePlex site, source code and all. It was also developed using test-driven develop-
ment as the software construction technique. Full unit test coverage is included in the
source code download, and
ASP.NET MVC 1.0 was released under the MS-PL, and OSI-
approved open source license.

ASP.NET MVC works the way the web works; it’s a natural fit. Although Microsoft is
last to the table with a Model-View-Controller framework for its development plat-
form, this framework is a strong player. Its design focuses on the core abstractions
first. It is conducive to extension by the community. In fact, the same week the first
Community Technology Preview (
CTP) was released, Eric Hexter and I launched the
MvcContrib open-source project with an initial offering of extensions that integrated
with the
ASP.NET MVC Framework.
At the time of publishing this book, the
ASP.NET MVC framework is a frequently
used tool at Headspring Systems, where I facilitate the consulting practice. For the
.
NET industry as a whole, I predict that ASP.NET MVC will be considered the norm for
ASP.NET development by 2011.
New developers are coming to the .
NET platform every day, and for web develop-
ers,
ASP.NET MVC is easy to adopt and learn. Because of the decreased complexity, the
barrier to adoption is lowered, and because of the simplicity, it can grow to meet the
demands of some of the most complex enterprise systems.
When Manning Publications approached me to write a book on
ASP.NET MVC, I

was already a frequent blogger on the topic and had published an article on the
framework in CoDe magazine. Even so, I knew writing a book would be a tremendous
challenge. This book has been in progress for over a year, and I am excited to see it
published. I learned quite a bit from Ben and Jimmy throughout this project, and I
learned so much more about the framework by writing about it. This knowledge has
direct and immediate benefit to our client projects.
Our hope is that our book will stay with you even after you have written your first
application. Writing a book published just after a 1.0 release is challenging because
many things are discovered after a technology has been out in the wild. Leveraging it
on client projects immediately has definitely helped increase the quality of informa-
tion contained in the book because it is derived from hands-on experience.
Although other platforms have benefited from Model-View-Controller frameworks
for many years, the
MVC pattern is still foreign to many .NET developers. This book
explains how and when to use the framework; also the theory and principles behind
the pattern as well as complimentary patterns. We hope that this book will enlighten
your understanding of an indispensable technology that’s simple to learn.
J
EFFREY PALERMO
Licensed to Gayle M. Noll <>
Download at Boykma.Com
xviii
acknowledgments
We’d like to thank Scott Guthrie for seeing the need in the .NET space for this frame-
work. Without his prototype, vision, and leadership, this offering would still not exist
in the .NET framework. We would also like to recognize the core
ASP.NET MVC team
at Microsoft, headed by Phil Haack, the Program Manager for
ASP.NET MVC. Other
key members of the

ASP.NET MVC team are Eilon Lipton (Lead Dev), Levi Broderick
(Dev), Jacques Eloff (Dev), Carl Dacosta (
QA), and Federico Silva Armas (Lead QA).
We would also like to extend our thanks to the large number of additional staff who
worked on packaging, documenting and delivering the
ASP.NET MVC framework as a
supported offering from Microsoft. Even though this framework is small compared to
others, this move from Microsoft is shifting the mental inertia of the .NET portion of
the software industry.
This book employed three working authors, all consultants with multiple projects,
along with startup help and a chapter draft by Dave Verwer. The book efforttook over
a year and a half, starting with the first Community Technology Preview of the
ASP.NET MVC Framework. This dynamic required tremendous support from the staff
at Manning Publications. We would like to thank them for their patience and support
throughout the project. In particular, we would like to thank acquisitions editor
Michael Stephens and editor Tom Cirtin for their leadership. Michael saw the need
for this book and contacted me about writing it. Tom was very supportive and patient
and helped the three of us through our first book publication.
Our independent technical reviewers were outstanding. They offered advice and
opinionated viewpoints on each chapter during development, and without that input,
Licensed to Gayle M. Noll <>
Download at Boykma.Com
ACKNOWLEDGMENTS
xix
the book would not be as good as we hope it is. Our sincere thanks goes to Phil Haack
for reviewing the manuscript and writing a brilliant foreword. Many thanks should
also go to Freedom Dumlao, who painstakingly reviewed each chapter to ensure the
message would apply in the best manner to the target audience. Jeremy Skinner was
also a boon to the project. Jeremy tested and retested every code listing and code sam-
ple in the book as well as in the many Visual Studio projects that come with the book.

His attention to detail, backed up by his vast experience with
ASP.NET MVC and Mvc-
Contrib, has contributed greatly to this book.
Manning invited the following reviewers to read the manuscript at different stages
of development and to send their comments: Mark Monster, Andrew Siemer, Benja-
min Day, Frank Wang, Derek Jackson, Tim Binkley-Jones, Marc Gravell, Alessandro
Gallo, Josh Heyer, Peter Johnson, Jeremy Anderson, and Alex Thissen.
This book has also benefited from outside technical reviewers who volunteered to
read parts of the manuscript and provided feedback: Rod Paddock, Craig Shoemaker,
Hamilton Verissimo, Matt Hinze, Kevin Hurwitz, Blake Caraway, Nick Becker, Mahen-
dra Mavani, Eric Anderson, Rafael Torres, Eric Hexter, Tom Jaeschke, Matt Hawley,
and Sebastien Lambla.
Before this book went to print, a large number of people purchased the
PDF edi-
tion of the book by participating in the
MEAP, Manning’s Early Access Program. We
would like to thank those readers for their comments and participation early, and
throughout the manuscript portion of the project, especially Eric Kinateder, Ben
Mills, Peter Kellner, Jeff P., Orlando Agostinho, Liam McLennan, Ronald Wildenberg,
Max Fraser, Gudmundur.Hreidarsson, Kyle Szklenski, Philippe Vialatte, Lars Zeb,
Marc Gravell, Cody Skidmore, Mark Fowler, Joey Beninghove, Shadi Mari, Simone
Chiaretta, Jay Smith, Jeff Kwak, and Mohammad Azam.
JEFFREY PALERMO
I would like to thank my beautiful wife, Liana, for her support and patience through-
out this project. Liana gave birth to our daughter, Gwyneth Rose, shortly before the
book was started, and the motivation to spend more time with my growing family
pushed me to complete the book. Thanks also to my parents, Peter and Rosemary Pal-
ermo, for instilling in me a love of books and learning from an early age.
BEN SCHEIRMAN
My thanks and utmost appreciation go out to my amazing wife, Silvia. Her continued

support and encouragement of my extracurricular work led to writing this book in the
first place. I would also like to recognize one of my university mentors, Venkat Subra-
maniam. With his guidance, I found my passion in software development and strived
to learn more and push the envelope. He was an inspiration in my career. Finally I’d
like to thank my wonderful children, Andréa, Noah, and Ethan (and most recently
Isaac and Isabella), who showed immense patience and encouragement while their
dad was banging away at the keyboard in the late hours of the night.
Licensed to Gayle M. Noll <>
Download at Boykma.Com
ACKNOWLEDGMENTS
xx
JIMMY BOGARD
Thanks to my wife, Sara, without whose love, support, and patience, my contribution
to this project would not have been possible. Also, thanks to my family for putting up
with a strange little bookworm all those years. Finally, thanks to my high school com-
puter science teacher, Scotty Johnson, who showed me the rewards that a true passion
for the craft can bring.
Licensed to Gayle M. Noll <>
Download at Boykma.Com
xxi
about this book
The ASP.NET MVC Framework was a vision of Scott Guthrie in early 2007. With a proto-
type demonstration in late 2007 as well as a key hire of Phil Haack as the Senior Pro-
gram Manager of the feature team, Scott made the vision a reality. At a time when the
.
NET community was becoming frustrated that other platforms had great MVC frame-
works like Tapestry, Rails, and so on, Web Forms was losing favor as developers strug-
gled to make it do things previously unimagined when it became public in 2001. Castle
MonoRail was a very capable framework and continues to have strong leadership
behind it, but the broader .

NET industry needed a change from Web Forms. Phil
Haack, with his experience outside of Microsoft as well as in the open source commu-
nity, immediately came in and led the
ASP.NET MVC Framework team to a successful 1.0
release that the .
NET community is excited about.

ASP.NET MVC has the benefit of lessons learned from other popular MVC frame-
works such as Struts, WebWork, Tapestry, Rails, and MonoRail. It also came about as
C# starts to push away its fully statically typed roots. The language enhancements
introduced with .
NET 3.5 have been fully leveraged in the ASP.NET MVC Framework,
giving it a huge advantage over frameworks that came before as well as all the Java
frameworks that are tied to the currently supported Java syntax.
For people who have a diversified software background,
ASP.NET MVC is a great
addition to the Visual Studio development experience. For those who began their
software career with .
NET 1.0 or later, it is a fundamental shift in thinking since they
grew up with Web Forms being “normal” web development.
This book attempts to start at a point that is past the documentation and online
tutorials available on the
ASP.NET MVC website at If you are
Licensed to Gayle M. Noll <>
Download at Boykma.Com
ABOUT THIS BOOK
xxii
just getting started with ASP.NET, you will want to read some of the older books cover-
ing the
ASP.NET pipeline and server runtime. Because ASP.NET MVC layers on to

ASP.NET, it is important to understand the fundamentals. If you are a current ASP.NET
developer, you will find that this book does not insult your intelligence. It is a fast-
paced book aimed at giving you the why and not just the how.
Since
ASP.NET MVC is a new technology offering you can expect several books
to cover the topic. This is a framework that is not sitting still. Since its release in
March 2009, several books have been released, but the community is finding new
and better ways to use the framework. The newest ideas make their way to the Mvc-
Contrib project, and to public release frequently as new additions are contributed.
Because of this dynamic, this book covers
ASP.NET MVC with MvcContrib sprinkled
throughout. The authors are all actively developing with the framework, and MvcCo-
ntrib plays a vital part in every application. This books aims to have a long-lasting
place on your bookshelf. The
API will evolve, but the principles behind using an
MVC framework as well as the ways to structure URLs, tests, and application layers are
more durable. With this, we hope that this book serves not only as a rigorous foray
into
ASP.NET MVC development but also as a guide toward developing long-lived web
applications on the .
NET platform.
We hope that the arrival of this book is considered good timing because the text
was written with the perspective of the roadmap of
ASP.NET MVC 2.0 in mind. With the
roadmap plans released and the first
CTP of v2 already available, the techniques in this
book are useful now and are also relevant for
ASP.NET MVC v2, which is quickly
approaching. We hope this book will help you start on your way to creating many
maintainable, long-lived applications on the new version of

ASP.NET.
Who should read this book?
This book is written for senior developers working with ASP.NET. The authors are
senior and strong leaders in their companies, local community, and the industry. All
three authors are recognized by Microsoft with the Microsoft Most Valuable Profes-
sional (
MVP) award. With that in mind, we felt it appropriate to write a book aimed at
senior members of the software team. With the market flooded with beginner books
and books that reformat online documentation and tutorials, we attempted to write a
book that might leave some beginners behind but at the same time challenge senior
developers and architects. Whether or not you are familiar with other
MVC frame-
works, this book will push your knowledge further than you are accustomed to when
reading a technology book.
The book comes with a full reference implementation in production at http://
CodeCampServer.com. CodeCampServer was developed by the authors and is open
source with many other contributors at this time. CodeCampServer is an
ASP.NET MVC
application aimed at hosting user group websites and websites for .NET user group
conferences, frequently called Code Camps. The codebase was developed using Onion
Architecture, domain-driven design, test-driven development, and inversion of con-
trol. The techniques espoused in the book are implemented in the project. Many of
Licensed to Gayle M. Noll <>
Download at Boykma.Com
ABOUT THIS BOOK
xxiii
the code examples in the book are detailed explorations of parts of CodeCampServer.
Although the project will continue to evolve after this book is published, the princi-
ples with which it and the text were written are timeless and portable beyond a single
version of the technology.

Because in any real project, like CodeCampServer, you use many libraries for specific
things, we did not shy away from using these as well. We feel that avoiding other libraries
for the sake of simplicity also makes it difficult for the reader to apply the knowledge
gained while reading. With that in mind, we use popular libraries such as MvcContrib,
NAnt, NUnit, StructureMap, Windsor, Castle, RhinoMocks, Log4Net, NHibernate,
Tarantino, AutoMapper, Iesi.Collections and many others. Because real projects have a
collage of libraries, we felt that learning
ASP.NET MVC in this realistic setting was most
appropriate. We have taken care to separate concerns when necessary. We always sepa-
rate data access from the domain model and the presentation layer, and we separate pre-
sentation model from views; you will not see simplistic examples such as performing a
query directly from a
UI controller. This is bad practice in anything but the most trivial
applications such as that serving (a three-page site).
Real applications have many screens, the embedding data access and other logic in the
UI is a recipe for a codebase that is very costly to maintain.
We’ve done our best to call out where we expect existing
ASP.NET knowledge to tie
the example together, but if you find yourself wondering what an
HTTP module is, you
will probably want to read one of the earlier
ASP.NET books.
Roadmap
Chapter 1 throws the reader directly into code by picking apart the default project
template. After a primer on routes, the text moves through a simple controller and
view and moves to initial maintainability. The chapter follows up by covering the
basics of testing controllers.
Chapter 2 moves into the model. It covers not only the domain model of the appli-
cation but also the need for different types of models depending on usage, such as a
presentation model. Because the authors consider using a presentation model, com-

monly called view model, essential for the maintainability for nontrivial systems, it is
used right away.
Chapter 3 covers controller details. The controller can be very simple or quite
complex, and the text covers both. The chapter explores working with form values
and querystring values, and it covers model binding, which is one of the most-needed
abstractions for
ASP.NET to date. Chapter 3 concludes after outlining all the available
extension points that are built in.
Chapter 4 gives further insight into views. After outlining the key abstractions in
the default view engine, it pulls the reader along to essential concepts such as layouts,
partial views, and building your own validation and HTML helpers.
Chapter 5 goes deeper than you will ever need into routing. Although most proj-
ects will not need this amount of advanced routing, we explore the topic thoroughly.
We cover the why and not just the how of crafting
URLs. From designing a URL schema
Licensed to Gayle M. Noll <>
Download at Boykma.Com
ABOUT THIS BOOK
xxiv
to adding dynamic routes, this chapter is a comprehensive guide to the most flexible
routes you will need.
Chapter 6 explores the many ways to customize and extend the
ASP.NET MVC
Framework. It starts with custom route handlers and moves to when, why, and how to
create your own controller factory. Two Inversion of Control containers are covered in
the controller factory section: Windsor and StructureMap. Because most nontrivial
applications will want to use a custom controller factory, this section is covered thor-
oughly. Next the chapter moves through the ways to extend the controller with action
invokers and filters. After a custom view engine and using the new T4 templates, the
reader will have the full picture of the available extension points.

Chapter 7 communicates ways to scale the architecture for more complex sites.
The first is solving the problem of large controller actions and how to move multiple,
ill-placed responsibilities out of the controller. View helpers are also covered in more
detail as well as techniques for segmenting large views into a number of cohesive
smaller ones. The chapter also covers larger issues encountered with action filters.
Chapter 8 offers ways to leverage existing
ASP.NET features in an ASP.NET MVC appli-
cation. The text covers how to use existing server controls, then moves to caching, both
output caching and using request level caching provided by
HttpContext.Items
. It then
moves through tracing, health monitoring, site maps, personalization, localization,
linq, cookies, session state, and configuration. Because
ASP.NET MVC is an add-on to
ASP.NET and not a replacement, this chapter ensures the reader understands where all
these existing features fit.
Chapter 9 has been one of the most popular chapters in the early access program
because now, in mid-2009,
AJAX is a hot topic. We first lay down our opinionated view
on
AJAX and then outline the most common uses and techniques for it starting with
simple
HTML replacement. The chapter covers implementing a REST API with con-
trollers as well as some of the third-party libraries and controls available for
AJAX. The
chapter also outlines ways to make controller actions automatically support
AJAX.
Chapter 10 covers hosting and deployment. Though not as sexy of a topic as
AJAX, it is critical to understand how to deploy applications built on this framework
to

IIS5/6/7/7.5. All versions are covered in detail as well as the implications of using
extensions, wildcard mappings, and
URL rewriting. After covering XCopy deploy-
ment, the chapter delivers techniques for managing production and development
environment settings. The chapter closes out with an autodeployment example that
is similar to how CodeCampServer is autodeployed in the wild.
Chapter 11 explores MonoRail and Ruby on Rails as a comparison and benchmark
against
ASP.NET MVC. It starts out with MonoRail and covers validation, data access
with ActiveRecord, as well as the view engine choices. Rails follows closely on its heels
with “The Rails Way,” ActiveRecord and ActionPack. The purpose of the chapter is to
give the reader some familiarity with competing
MVC frameworks because good ideas
come from everywhere.
Licensed to Gayle M. Noll <>
Download at Boykma.Com

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×