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

Professional ASP.NET MVC 1.0 pot

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 (18.38 MB, 460 trang )

www.dbebooks.com - Free Books & magazines
www.it-ebooks.info
Professional
ASP.NET MVC 1.0
Enhance Your Knowledge
Advance Your Career
ASP.NET MVC 1.0 Website Programming
Problem - Design - Solution
978-0-470-41095-0
A hands-on guide to creating ASP.NET websites using MVC. The
complete example site is based on updating Marco Bellinaso’s
TheBeerHouse ASP.NET 2.0 application MVC.
Professional ASP.NET MVC 1.0
978-0-470-38461-9
Professional ASP.NET MVC 1.0 is a step-by-step tutorial on the theory
and approach for using ASP.NET MVC, and is full of real-world examples
for experienced developers to use in porting and creating their current
ASP.NET web sites. The tutorials are wrapped around growing a real-
world application using MVC, and feature toolsets and technologies that
compliment MVC such as SubSonic, LINQ, jQuery, and REST.
Professional ASP.NET 3.5 AJAX
978-0-470-39217-1
Discover how to use the ASP.NET AJAX features to create richer, more
responsive dynamic web sites. This book explains the architecture,
including the ASP.NET server elements and the client-side Javascript
library and runtime, and it walks the user through examples for each
feature element demonstrating how the client and server interact to
produce a better web application.
Professional ASP.NET 3.5 SP1: In C# and VB
978-0-470-47826-4
Updated edition of the bestselling ASP.NET book, expanded to cover


key SP1 data features including. ADO.NET Entity Framework, ADO.NET
Dynamic Data, and ADO.NET Data Services. This SP1 edition also adds
updated ASP.NET AJAX and jQuery coverage, a CD-ROM with free Wrox
Blox and a PDF of the book, and a hardcover for durability.
Beginning ASP.NET MVC 1.0
978-0-470-43399-7
Beginning ASP.NET MVC 1.0 is for developers who have .NET and ASP.NET experience, but want to enhance their level of
knowledge and need to learn about the MVC framework. The book covers all the main topics about ASP.NET MVC, and applies
all of the latest Microsoft technologies to demonstrate the benefits of its usage.
Beginning ASP.NET 3.5: In C# and VB
978-0-470-18759-3
Beginning ASP.NET 3.5 helps readers learn to build dynamic database driven web sites using ASP.NET 3.5. Starting from
scratch, the reader will progressively learn how to design and create web sites with interactive elements. After reading this book,
the reader should be able to build a database driven web site on her own, using best practices and current standards.
spine=.912"
Get more out of
WROX.com
Programmer to Programmer

Interact
Take an active role online by participating in
our P2P forums
Wrox Online Library
Hundreds of our books are available online
through Books24x7.com
Wrox Blox
Download short informational pieces and
code to keep you up to date and out of
trouble!
Chapters on Demand

Purchase individual book chapters in pdf
format
Join the Community
Sign up for our free monthly newsletter at
newsletter.wrox.com
Browse
Ready for more Wrox? We have books and
e-books available on .NET, SQL Server, Java,
XML, Visual Basic, C#/ C++, and much more!
Contact Us.
We always like to get feedback from our readers. Have a book idea?
Need community support? Let us know by e-mailing
www.it-ebooks.info
Professional ASP.NET MVC 1.0
Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xvii
Chapter 1: NerdDinner . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Chapter 2: Model-View-Controller and ASP.NET . . . . . . . . . . . . . . . . . . . . . . 165
Chapter 3: ASP.NET > ASP.NET MVC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175
Chapter 4: Routes and URLs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
Chapter 5: Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225
Chapter 6: Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251
Chapter 7: AJAX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277
Chapter 8: Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305
Chapter 9: Securing Your Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325
Chapter 10: Test Driven Development with ASP.NET MVC . . . . . . . . . . . . . . 349
Chapter 11: Testable Design Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367
Chapter 12: Best of Both Worlds: Web Forms and MVC Together . . . . . . . . 393
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421
84619book.indb Listi84619book.indb Listi 3/30/09 2:56:51 PM3/30/09 2:56:51 PM
www.it-ebooks.info

84619book.indb Listii84619book.indb Listii 3/30/09 2:56:51 PM3/30/09 2:56:51 PM
www.it-ebooks.info
Professional
ASP.NET MVC 1.0
Rob Conery
Scott Guthrie
Phil Haack
Scott Hanselman
84619book.indb Listiii84619book.indb Listiii 3/30/09 2:56:51 PM3/30/09 2:56:51 PM
www.it-ebooks.info
Professional ASP.NET MVC 1.0
Published by
Wiley Publishing, Inc.
10475 Crosspoint Boulevard
Indianapolis, IN 46256
www.wiley.com.
Copyright © 2009 by Wiley Publishing, Inc., Indianapolis, Indiana
Published simultaneously in Canada
ISBN: 978-0-470-38461-9
Manufactured in the United States of America
10 9 8 7 6 5 4 3 2 1
Library of Congress Cataloging-in-Publication Data is available from the publisher.
No part of this publication may be reproduced, stored in a retrieval system or transmitted in any form
or by any means, electronic, mechanical, photocopying, recording, scanning or otherwise, except as
permitted under Sections 107 or 108 of the 1976 United States Copyright Act, without either the prior
written permission of the Publisher, or authorization through payment of the appropriate per-copy
fee to the Copyright Clearance Center, 222 Rosewood Drive, Danvers, MA 01923, (978) 750-8400, fax
(978) 646-8600. Requests to the Publisher for permission should be addressed to the Permissions
Department, John Wiley & Sons, Inc., 111 River Street, Hoboken, NJ 07030, (201) 748-6011, fax
(201) 748-6008, or online at

www.wiley.com/go/permissions.
Limit of Liability/Disclaimer of Warranty: The publisher and the author make no representations or war-
ranties with respect to the accuracy or completeness of the contents of this work and specifi cally disclaim all
warranties, including without limitation warranties of fi tness for a particular purpose. No warranty may be
created or extended by sales or promotional materials. The advice and strategies contained herein may not
be suitable for every situation. This work is sold with the understanding that the publisher is not engaged in
rendering legal, accounting, or other professional services. If professional assistance is required, the services
of a competent professional person should be sought. Neither the publisher nor the author shall be liable for
damages arising herefrom. The fact that an organization or web site is referred to in this work as a citation
and/or a potential source of further information does not mean that the author or the publisher endorses the
information the organization or web site may provide or recommendations it may make. Further, readers
should be aware that Internet web sites listed in this work may have changed or disappeared between when
this work was written and when it is read.
For general information on our other products and services please contact our Customer Care Department
within the United States at (877) 762-2974, outside the United States at (317) 572-3993 or fax (317) 572-4002.
Trademarks: Wiley, the Wiley logo, Wrox, the Wrox logo, Wrox Programmer to Programmer, and related
trade dress are trademarks or registered trademarks of John Wiley & Sons, Inc. and/or its affi liates, in the
United States and other countries, and may not be used without written permission. All other trademarks
are the property of their respective owners. Wiley Publishing, Inc., is not associated with any product or
vendor mentioned in this book.
Wiley also publishes its books in a variety of electronic formats. Some content that appears in print may not
be available in electronic books.
84619book.indb Listiv84619book.indb Listiv 3/30/09 2:56:52 PM3/30/09 2:56:52 PM
www.it-ebooks.info
To my sweet wife Kathy, who inspires me everyday.
— Rob Conery
My wife, Akumi, deserves to have her smiling face on the cover as much as I do, for all
her support made this possible. And thanks to Cody for his infectious happiness.
— Phil Haack
Thanks to my wife Mo and my sons Zenzo and Thabo for their unlimited supply of smooches.

— Scott Hanselman
84619book.indb Listv84619book.indb Listv 3/30/09 2:56:52 PM3/30/09 2:56:52 PM
www.it-ebooks.info
About the Authors
Rob Conery works at Microsoft on the ASP.NET team. He is the creator of SubSonic and was the chief
architect of the Commerce Starter Kit (a free, Open Source eCommerce platform for .NET). He lives in
Kauai, Hawaii, with his wife and two daughters (Maddy and Ruby).
Scott Guthrie is corporate vice president of Microsoft’s .NET Developer Division, where he runs the
development teams responsible for delivering Microsoft Visual Studio developer tools and Microsoft .NET
Framework technologies for building client and Web applications. A founding member of the .NET project,
Guthrie has played a key role in the design and development of Visual Studio and the .NET Framework
since 1999. Guthrie is also responsible for Microsoft’s web server platform and development tools teams.
He has also more recently driven the development of Silverlight — a cross browser, cross platform plug-in
for delivering next generation media experiences and rich Internet applications for the Web. Today, Guthrie
directly manages the development teams that build the Common Language Runtime (CLR), ASP.NET,
Silverlight, Windows Presentation Foundation (WPF), IIS, Commerce Server, and the Visual Studio Tools
for web, client, and Silverlight development. Guthrie graduated with a degree in computer science from
Duke University.
Phil Haack is a senior program manager with the ASP.NET team working on the ASP.NET MVC project.
Prior to joining Microsoft, Phil worked as a product manager for a code search engine, a dev manager
for an online gaming company, and a senior architect for a popular Spanish language television net-
work, among other crazy pursuits. As a code junkie, Phil Haack loves to craft software. Not only does he
enjoy writing software, but he also enjoys writing about software and software management on his blog,
. In his spare time, Phil contributes to various Open Source projects and is the
founder of the Subtext blog engine project, which is undergoing a rewrite, using ASP.NET MVC, of course.
Scott Hanselman works for Microsoft as a principal program manager in the Developer Division,
aiming to spread the good word about developing software, most often on the Microsoft stack.
Before this, he worked in eFinance for 6+ years and before that he was a principal consultant and a
Microsoft Partner for nearly 7 years. He was also involved in a few things like the MVP and RD pro-
grams and will speak about computers (and other passions) whenever someone will listen to him.

He blogs at
www.hanselman.com and podcasts at www.hanselminutes.com and contributes to sites
like
www.asp.net, www.windowsclient.net, and www.silverlight.net. You can also fi nd him
on Twitter, far too often.
84619book.indb Listvi84619book.indb Listvi 3/30/09 2:56:52 PM3/30/09 2:56:52 PM
www.it-ebooks.info
Associate Publisher
Jim Minatel
Development Editor
Maureen Spears
Technical Editors
Levi Broderick
Darren Kindberg
Production Editor
Kathleen Wisor
Copy Editor
Foxxe Editorial Services
Editorial Manager
Mary Beth Wakefi eld
Production Manager
Tim Tate
Vice President and Executive Group Publisher
Richard Swadley
Vice President and Executive Publisher
Barry Pruett
Project Coordinator, Cover
Lynsey Stanford
Compositor
Craig Woods, Happenstance Type-O-Rama

Proofreader
Nancy C. Hanger, Windhaven
Indexer
J&J Indexing
Credits
84619book.indb Listvii84619book.indb Listvii 3/30/09 2:56:52 PM3/30/09 2:56:52 PM
www.it-ebooks.info
Acknowledgments
Thanks to my wife for her unfl agging support. When Scott Guthrie showed me this “pet project,”
I told him I just had to work on it, so thanks to The Gu for helping to make that possible. Thanks to
Levi Broderick for all his editing help, to Brad Wilson for reviewing the chapter on TDD (I still owe you
a beer or two), to Eilon Lipton, the lead developer on ASP.NET MVC, for all his deep insight, and to the
rest of the MVC feature team (Carl, Fede, Jon, Keith, Simon etc.) for being so much fun to work with.
— Phil Haack
Thanks to The Gu, and my boss Simon for their support in working on this book. Thanks to Phil Haack,
Eilon Lipton, Levi Broderick, and all the ASP.NET MVC guys for making such a rockin’ sweet framework.
— Scott Hanselman
84619book.indb Listviii84619book.indb Listviii 3/30/09 2:56:52 PM3/30/09 2:56:52 PM
www.it-ebooks.info
Contents
Introduction xvii
NerdDinner Chapter 1: 1
File ➪ New Project 5
Examining the NerdDinner Directory Structure 7
Running the NerdDinner Application 9
Testing the NerdDinner Application 12
Creating the Database 13
Creating a New SQL Server Express Database 14
Creating Tables within Our Database 15
Setting Up a Foreign Key Relationship Between Tables 18

Adding Data to Our Tables 20
Building the Model 20
LINQ to SQL 21
Adding LINQ to SQL Classes to Our Project 21
Creating Data Model Classes with LINQ to SQL 22
NerdDinnerDataContext Class 25
Creating a DinnerRepository Class 26
Retrieving, Updating, Inserting, and Deleting Using the DinnerRepository Class 28
Integrating Validation and Business Rule Logic with Model Classes 30
Controllers and Views 34
Adding a DinnersController Controller 35
Adding Index and Details Action Methods to the DinnersController Class 36
Understanding ASP.NET MVC Routing 37
Using the DinnerRepository from Our DinnersController 39
Using Views with Our Controller 40
Implementing the “NotFound” View Template 42
Implementing the “Details” View Template 44
Implementing the “Index” View Template 49
Convention-Based Naming and the \Views Directory Structure 54
Create, Update, Delete Form Scenarios 56
URLs Handled by DinnersController 56
Implementing the HTTP-GET Edit Action Method 57
Html.BeginForm and Html.TextBox Html Helper Methods 61
Implementing the HTTP-POST Edit Action Method 62
84619book.indb Listix84619book.indb Listix 3/30/09 2:09:08 PM3/30/09 2:09:08 PM
www.it-ebooks.info
x
Contents
Handling Edit Errors 66
Understanding ModelState and the Validation HTML Helper Methods 68

Using a AddRuleViolations Helper Method 70
Complete Edit Action Method Implementations 71
Implementing the HTTP-GET Create Action Method 72
Implementing the HTTP-POST Create Action Method 74
Implementing the HTTP-GET Delete Action Method 78
Implementing the HTTP-POST Delete Action Method 80
Model Binding Security 82
CRUD Wrap-Up 83
ViewData and ViewModel 86
Passing Data from Controllers to View Templates 86
Using the ViewData Dictionary 87
Using a ViewModel Pattern 89
Custom-Shaped ViewModel Classes 92
Partials and Master Pages 92
Revisiting Our Edit and Create View Templates 92
Using Partial View Templates 93
Using Partial View Templates to Clarify Code 97
Master Pages 98
Paging Support 101
Index() Action Method Recap 102
Understanding IQueryable<T> 102
Adding a “page” Value to the URL 103
Adding Page Navigation UI 106
Authentication and Authorization 110
Understanding Authentication and Authorization 110
Forms Authentication and the AccountController 111
Authorizing the /Dinners/Create URL Using the [Authorize] Filter 114
Using the User.Identity.Name Property When Creating Dinners 116
Using the User.Identity.Name Property When Editing Dinners 116
Showing/Hiding Edit and Delete Links 118

AJAX Enabling RSVPs Accepts 119
Indicating Whether the User Is RSVP’ed 120
Implementing the Register Action Method 122
Calling the Register Action Method Using AJAX 123
Adding a jQuery Animation 125
Cleanup — Refactor out a RSVP Partial View 127
Integrating an AJAX Map 127
Creating a Map Partial View 127
Creating a Map.js Utility Library 129
Integrating the Map with Create and Edit Forms 131
84619book.indb Listx84619book.indb Listx 3/30/09 2:09:08 PM3/30/09 2:09:08 PM
www.it-ebooks.info
xi
Contents
Integrating the Map with the Details View 135
Implementing Location Search in Our Database and Repository 136
Implementing a JSON-Based AJAX Search Action Method 140
Calling the JSON-Based AJAX Method Using jQuery 141
Unit Testing 145
Why Unit Test? 145
NerdDinner.Tests Project 146
Creating Unit Tests for Our Dinner Model Class 147
Running Tests 149
Creating DinnersController Unit Tests 150
Dependency Injection 152
Extracting an IDinnerRepository Interface 152
Updating DinnersController to Support Constructor Injection 154
Creating the FakeDinnerRepository Class 154
Using the FakeDinnerRepository with Unit Tests 157
Creating Edit Action Unit Tests 159

Mocking the User.Identity.Name Property 160
Testing UpdateModel() Scenarios 162
Testing Wrap-Up 163
NerdDinner Wrap-Up 164
Model-View-Controller and ASP.NET 16Chapter 2: 5
What Is Model-View-Controller? 165
MVC on the Web Today 167
Ruby on Rails 168
Django and Python 169
Spring, Struts, and Java 169
Zend Framework and PHP 170
MonoRail 170
ASP.NET MVC: The New Kid on the Block 170
Serving Methods, Not Files 171
Is This Web Forms 4.0? 171
Why Not Web Forms? 172
Cost/Benefi t of Web Forms 172
Should You Fear ASP.NET MVC? 173
Summary 174
ASP.NET > ASP.NET MVC 17Chapter 3: 5
Abstraction: What Web Forms Does Well 175
A Basic Web Forms Application 176
The Importance of Events 180
84619book.indb Listxi84619book.indb Listxi 3/30/09 2:09:08 PM3/30/09 2:09:08 PM
www.it-ebooks.info
xii
Contents
The Leak: Where Web Forms Doesn’t Exactly Fit 181
ViewState 183
Controlling Your Angle Brackets 183

Client IDs 183
Testing 183
Back to Basics: ASP.NET MVC Believes . . . 184
Orchestration versus Composing 184
Separation of Concerns: What It Means 184
Approaches to Maintainability 185
Caring About Testability 186
Common Reactions to ASP.NET MVC 187
This Looks Like Classic ASP from 1999! 187
Who Moved My “<asp:Cheese runat=“server”> 187
Yet Another Web Framework 188
Why “(ASP.NET > ASP.NET MVC) == True” 188
Convention over Confi guration 190
Your First, er, Third, Request 194
The Request Lifecycle 196
Summary 196
Routes and URLs 19Chapter 4: 7
Introduction to Routing 198
Compared to URL Rewriting 199
Defi ning Routes 199
Named Routes 206
Catch-All Parameter 206
StopRoutingHandler 208
Under the Hood: How Routes Generate URLs 209
Under the Hood: How Routes Tie Your URL to an Action 216
The High-Level Request Routing Pipeline 217
Route Matching 217
Advanced Routing with Custom Constraints 217
Route Extensibility 218
Using Routing with Web Forms 222

Summary 224
Controllers 22Chapter 5: 5
History of the Controller 225
Defi ning the Controller: The IController Interface 227
The ControllerBase Abstract Base Class 229
The Controller Class and Actions 229
Action Methods 230
84619book.indb Listxii84619book.indb Listxii 3/30/09 2:09:08 PM3/30/09 2:09:08 PM
www.it-ebooks.info
xiii
Contents
The ActionResult 233
Action Result Types 235
Action Result Helper Methods 238
Implicit Action Results 239
Action Invoker 240
How an Action Is Mapped to a Method 241
Mapping Parameters 243
Invoking Actions 244
Passing Data to Actions: The Model Binders 244
A Word About User Input 248
Summary 249
Views 25Chapter 6: 1
What a View Does 251
What a View Shouldn’t Do 253
Specifying a View 253
Strongly Typed Views 255
HTML Helper Methods 257
HtmlHelper Class and Extension Methods 257
Using the HTML Helpers 258

The View Engine 266
Confi guring a View Engine 267
Selecting a View Engine 267
Finding a View 268
The View Itself 269
Alternative View Engines 269
New View Engine or New ActionResult? 275
Summary 275
AJAX 27Chapter 7: 7
When AJAX Is Cool 278
When It’s Not 278
AJAX Examples 280
Handling Disabled Scripting 280
Using Partials for Rendering 284
Some Things You May Not Know About Microsoft ASP.NET AJAX 288
Updating an HTML Element When Submitting a Form 290
The Auto-Complete Text Box 292
Implementing Auto-Complete with Microsoft ASP.NET AJAX 292
Filtering Data with a Selectbox 295
84619book.indb Listxiii84619book.indb Listxiii 3/30/09 2:09:09 PM3/30/09 2:09:09 PM
www.it-ebooks.info
xiv
Contents
The Modal Popup with jQuery 296
The Modal Popup Code 297
The Rating Control 299
Summary 303
Filters 30Chapter 8: 5
Filters Included with ASP.NET MVC 305
Authorize 306

OutputCache 308
Exception Filter 310
Custom Filters 311
Writing a Custom Action Filter 316
Writing a Custom Authorization Filter 317
Writing a Custom Exception Filter 319
Filter Ordering 320
Filter Naming 321
Summary 323
Securing Your Application 32Chapter 9: 5
This Is a War 327
Knowing Your Enemy’s Mind 327
Weapons 331
Spam 331
Case Study: Profi ting from Evil with the Srizbi and Storm Botnets 332
Digital Stealth Ninja Network 333
Threat: Cross-Site Scripting (XSS) 334
Passive Injection 334
Active Injection 336
Preventing XSS 338
Html.AttributeEncode and Url.Encode 338
Threat: Cross-Site Request Forgery 339
Preventing CSRF Attacks 342
Threat: Cookie Stealing 343
Preventing Cookie Theft with HttpOnly 344
Keeping Your Pants Up: Proper Error Reporting and the Stack Trace 345
Securing Your Controllers, Not Your Routes 345
Using [Authorize] to Lock Down Your Action or Controller 346
Using [NonAction] to Protect Public Methods 346
Whitelist Form Binding 347

Summary: It’s Up to You 348
84619book.indb Listxiv84619book.indb Listxiv 3/30/09 2:09:09 PM3/30/09 2:09:09 PM
www.it-ebooks.info
xv
Contents
Test Driven Development with ASP.NET MVC 34Chapter 10: 9
A Brief Introduction to TDD 350
What Does TDD Look Like? 350
Writing Good Unit Tests 353
What Are Some Benefi ts of Writing Tests? 357
How Do I Get Started? 357
Applying TDD to ASP.NET MVC 357
Testing Routes 358
Testing Controllers 360
Redirecting to Another Action 360
Testing View Helpers 362
Testing Views 364
Summary 365
Testable Design Patterns 36Chapter 11: 7
Why You Should Care About Testability 368
Big Design Up Front (BDUF) 368
Agile Software Development 369
You Want to Write Testable Code 370
Using Tests to Prove You’re Done 371
Designing Your Application for Testability 371
Future-Proofi ng Your Application with Interfaces 371
The Single Responsibility Principle 373
Avoid Using Singletons and Static Methods 373
Testable Data Access 376
Creating the Model 377

The Repository Pattern in Detail 379
Implementing Business Logic with the Service Layer 383
Services Gone Wild 385
Partial Solution: Setting Controller Dependencies Manually 386
Summary 392
Best of Both Worlds: Web Forms and MVC Together 39Chapter 12: 3
How Is It Possible? 393
Including MVC in Existing Web Forms Applications 394
Step 1: Referencing the Required Libraries 394
Step 2: Creating the Necessary Directories 395
Step 3: Updating the Web.confi g 396
84619book.indb Listxv84619book.indb Listxv 3/30/09 2:09:09 PM3/30/09 2:09:09 PM
www.it-ebooks.info
xvi
Contents
Adding Web Forms to an Existing ASP.NET MVC Application 398
The Easy Part: Do Nothing 399
When/Home/Isn’t/Home/ 401
Using System.Web.Routing to Route to Web Forms 401
Sharing Data Between Web Forms and MVC 402
Using HTTP POST 402
Using the ASP.NET Session 403
Using Cross-Page Posting 404
Using TempData 406
Migrating from Web Forms to MVC 407
Step 1: Create an Empty ASP.NET MVC Project with a Test Project 407
Step 2: Implement the Structure 408
Step 3: Add Images and Styling 410
Step 4: Setting Up Routing and Controllers 411
Step 5: Replacing Complex Server Controls 415

Step 6: Uploading Files and Working with Images 418
Summary 420
Index 421
84619book.indb Listxvi84619book.indb Listxvi 3/30/09 2:09:09 PM3/30/09 2:09:09 PM
www.it-ebooks.info
Introduction
Why does the world need Yet Another Web Framework?
This is the question that is most likely on your mind — or perhaps it’s what you were thinking when
you saw this book sitting on the shelf. We each asked ourselves this many times over the last few years.
Indeed there are many frameworks out there today fl avored with every buzzword the industry can think
of. In short, it’s easy to be skeptical. Yet as we, the authors, delve deeper into the latest and greatest web
framework, we’re each starting to realize just how far the industry has come in the last 10 years.
Rob began programming for the Web with Classic ASP in 1997 and was giddy with excitement. When .NET
came out, he remembers running around his offi ce, stopping everyone from working and explaining that
the world just tilted on its axis.
We all feel the same way about ASP.NET MVC. Not because it’s “something different” but because it
offers developers the ultimate chance to “do it their way.” You don’t like the way the platform renders
the View? Change it! Just about every part of the ASP.NET MVC Framework is “swappable” — if the
shoes pinch, get different shoes. Don’t like ties? Why not a bow tie? You’re totally in control.
ASP.NET MVC is a web framework that comes with a bunch of conventions to make your life easier
when you follow them, but if you don’t want them, the framework is quick to step out of your way so
that you can get your work done in the way you like.
This book is going to go into the “out-of-the-box” experience you’ll have with ASP.NET MVC, but more
importantly you’ll learn practical ways that you can extend ASP.NET MVC with your own magic —
then hopefully share that magic with others.
Because of this extensibility and attention to “doing it your way,” we’re happy to embrace Yet Another
Web Framework and hope you are willing to come along with us for the ride.
Who This Book Is For
This book is for web developers who are looking to add more complete testing to their web sites, and
who are perhaps ready for “something different.”

In some places, we assume that you’re somewhat familiar with ASP.NET Web Forms, at least peripher-
ally. There are a lot of ASP.NET Web Forms developers out there who are interested in ASP.NET MVC,
so there are a number of places in this book where we contrast the two technologies. Even if you’re not
already an ASP.NET developer, you might still fi nd these sections interesting for context, as well as for
your own edifi cation, as ASP.NET MVC may not be the web technology that you’re looking for.
It’s worth noting, yet again, that ASP.NET MVC is not a replacement for ASP.NET Web Forms. Many
web developers have been giving a lot of attention to other web frameworks out there (Ruby on Rails,
84619flast.indd Listxvii84619flast.indd Listxvii 3/31/09 5:34:34 AM3/31/09 5:34:34 AM
www.it-ebooks.info
Introduction
xviii
Django), which have embraced the MVC (Model-View-Controller) application pattern, and if you’re one
of those developers, or even if you’re just curious, this book is for you.
MVC allows for (buzzword alert!) a “greater separation of concerns” between components in your
application. We’ll go into the ramifi cations of this later on, but if it had to be said it in a quick sentence:
ASP.NET MVC is ASP.NET Unplugged. ASP.NET MVC is a tinkerer’s framework that gives you very fi ne-
grained control over your HTML and JavaScript, as well as complete control over the programmatic
fl ow of your application.
There are no declarative server controls in MVC, which some people may like, others may dislike. In the
future, the MVC team may add declarative view controls to the mix, but these will be far different from
the components that ASP.NET Web Forms developers are used to, in which a control encapsulates both the
logic to render the view and the logic for responding to user input etc. Having all that encapsulated in a
single control in the view would violate the “separation of concerns” so central to this framework. The lev-
els of abstraction have been collapsed, with all the doors and windows opened to let the air fl ow freely.
The fi nal analogy we can throw at you is that ASP.NET MVC is more of a motorcycle, whereas ASP.NET
Web Forms might be more like a minivan, complete with airbags and a DVD player in case you have kids
and you don’t want them to fi ght while you’re driving to the in-laws for Friday dinner. Some people like
motorcycles, some people like minivans. They’ll both get you where you need to go, but one isn’t techni-
cally better than the other.
How This Book Is Structured

This book is divided into three very broad sections, each comprising several chapters.
The fi rst third of the book is concerned with introducing the MVC pattern and how ASP.NET MVC
implements that pattern.
Chapter 1 starts off with a description of the Model-View-Controller pattern, explaining the basic con-
cepts of the pattern and providing a bit of its history. The chapter goes on to describe the state of the
MVC pattern on the Web today as it is implemented by various frameworks, such as ASP.NET MVC.
Chapter 2 covers the ways that ASP.NET MVC is different from ASP.NET Web Forms and how to get
ASP.NET MVC up and running.
Chapter 3 explores the structure of a standard MVC application and covers what you get out of the box.
It covers some of the conventions and the digs a little under the hood to take a look at the entire request
lifecycle for an ASP.NET MVC request.
Chapter 4 digs deep into routing to describe the role that URLs play in your application and how routing
fi gures into that. It also differentiates routing from URL rewriting and covers a bit on extending routing
and writing unit tests for routes.
Chapter 5 takes a look at controllers and controller actions — what they are and how to write them.
It also covers action results, which are returned by controller actions and what they are used for.
Chapters 6–7 cover views and view engines, and then add a little fl avor on top by examining the role
that AJAX plays in your views.
84619flast.indd Listxviii84619flast.indd Listxviii 3/31/09 5:34:34 AM3/31/09 5:34:34 AM
www.it-ebooks.info
Introduction
xix
The second third of the book focuses entirely on advanced techniques and extending the framework.
Chapter 8 goes into detail on action fi lters, which provide an extensibility point for adding cross-cutting
behaviors to action methods.
Chapter 9 covers security and good practices for building a secure application.
Chapter 10 covers various approaches to building and interacting with different types of services made
available over the Web.
Chapter 11 provides a brief introduction to Test Driven Development (TDD) as it applies to
ASP.NET MVC. It then goes on to examine real-world patterns and practices for building applications

that are testable.
The fi nal part of the book covers guidance and best practices as well as providing a look ahead at the
future of the ASP.NET MVC platform.
Chapter 12 goes into detail on how Web Forms and MVC fi t together and covers ways to have the two
coexist in the same application, as well as how to migrate an app from Web Forms to MVC.
We tried to organize the book in such a way that when you read it in order, each chapter builds on the
previous one. If you already familiar with ASP.NET MVC you might skip directly to Chapter 4 and go
from there.
What You Need to Use This Book
To use ASP.NET MVC, you’ll probably want a copy of Visual Studio. You can use Visual Studio 2008
Web Developer Express SP1 or any of the paid versions of Visual Studio 2008 (such as Visual Studio
2008 Professional). If you’re going to use the Web Developer Express edition of Visual Studio, you need
to confi rm that you’re using SP1. ASP.NET MVC requires that you use Web Application Projects (WAPs)
rather than Web Site Projects, and this functionality was added in SP1 of Web Developer Express.
You will also need to make sure that you have the .NET Framework 3.5 installed at minimum. The runtime
does not require .NET 3.5 SP1 to run.
The following list shows you where to go to download the required software.
Visual Studio or Visual Studio Express: ❑
www.microsoft.com/vstudio or
www.microsoft.com/express
ASP.NET MVC: ❑ www.asp.net/mvc
Conventions
To help you get the most from the text and keep track of what’s happening, we’ve used a number of
conventions throughout the book.
84619flast.indd Listxix84619flast.indd Listxix 3/31/09 5:34:34 AM3/31/09 5:34:34 AM
www.it-ebooks.info
Introduction
xx
Occasionally the product team will take a moment to provide an interesting aside, for bits of trivia, and
those will appear in boxes like this:

Product Team Aside: Boxes like this one hold tips, tricks, trivia from the
ASP.NET Product Team or some other information that is directly relevant
to the surrounding text.
Tips, hints and tricks to the current discussion are offset and placed in italics like this.
As for styles in the text:
We ❑ highlight new terms and important words when we introduce them.
We show keyboard strokes like this: Ctrl+A. ❑
We show fi le names, URLs, and code within the text like so: ❑
persistence.properties.
We present code in two different ways: ❑
In code examples, we highlight important code that we want to emphasize with a gray
background.
The gray highlighting is not used for code that’s less important in the present
context, or has been shown before.
Source Code
The main nerddinner.com code download is hosted at codeplex and the most up-to-date code will
always be available at
The original nerddinner.com code
that matches the code used in the book is hosted at wrox.com from the book page.
As you work through the examples in this book, you may choose either to type in all the code manu-
ally or to use the source code fi les that accompany the book. All of the source code used in this book is
available for downloading at
www.wrox.com. Once at the site, simply locate the book’s title (either by
using the Search box or by using one of the title lists) and click the Download Code link on the book’s
detail page to obtain all the source code for the book.
Because many books have similar titles, you may fi nd it easiest to search by ISBN; this book’s ISBN is
978-0-470-38461-9.
Once you download the code, just decompress it with your favorite compression tool. Alternately, you
can go to the main Wrox code download page at
www.wrox.com/dynamic/books/download.aspx to

see the code available for this book and all other Wrox books.
84619flast.indd Listxx84619flast.indd Listxx 3/31/09 5:34:34 AM3/31/09 5:34:34 AM
www.it-ebooks.info
Introduction
xxi
Errata
We make every effort to ensure that there are no errors in the text or in the code. However, no one is
perfect, and mistakes do occur. If you fi nd an error in one of our books, like a spelling mistake or faulty
piece of code, we would be very grateful for your feedback. By sending in errata you may save another
reader hours of frustration, and at the same time you will be helping us provide even higher-quality
information.
To fi nd the errata page for this book, go to
www.wrox.com and locate the title using the Search box or one
of the title lists. Then, on the book details page, click the Book Errata link. On this page, you can view all
errata that has been submitted for this book and posted by Wrox editors. A complete book list including
links to each book’s errata is also available at
www.wrox.com/misc-pages/booklist.shtml.
If you don’t spot “your” error on the Book Errata page, go to
www.wrox.com/contact/techsupport
.shtml
and complete the form there to send us the error you have found. We’ll check the information
and, if appropriate, post a message to the book’s errata page, and fi x the problem in subsequent editions
of the book.
p2p.wrox.com
For author and peer discussion, join the P2P forums at p2p.wrox.com. The forums are a Web-based
system for you to post messages relating to Wrox books and related technologies and interact with
other readers and technology users. The forums offer a subscription feature to e-mail you topics of
interest of your choosing when new posts are made to the forums. Wrox authors, editors, other industry
experts, and your fellow readers are present on these forums.
At

you will fi nd a number of different forums that will help you not only as you
read this book but also as you develop your own applications. To join the forums, just follow these steps:

1. Go to p2p.wrox.com, and click the Register link.

2. Read the terms of use, and click Agree.

3. Complete the required information to join as well as any optional information you wish to pro-
vide, and click Submit.

4. You will receive an e-mail with information describing how to verify your account and com-
plete the joining process.
You can read messages in the forums without joining P2P, but in order to post your own messages, you
must join.
Once you join, you can post new messages and respond to messages other users post. You can read
messages at any time on the Web. If you would like to have new messages from a particular forum
e-mailed to you, click the Subscribe to this Forum icon by the forum name in the forum listing.
For more information about how to use the Wrox P2P, be sure to read the P2P FAQs for answers to
questions about how the forum software works as well as many common questions specifi c to P2P
and Wrox books. To read the FAQs, click the FAQ link on any P2P page.
84619flast.indd Listxxi84619flast.indd Listxxi 3/31/09 5:34:35 AM3/31/09 5:34:35 AM
www.it-ebooks.info
84619flast.indd Listxxii84619flast.indd Listxxii 3/31/09 5:34:35 AM3/31/09 5:34:35 AM
www.it-ebooks.info
NerdDinner
The best way to learn a new framework is to build something with it. This fi rst chapter walks
through how to build a small, but complete, application using ASP.NET MVC, and introduces
some of the core concepts behind it.
The application we are going to build is called “NerdDinner.” NerdDinner provides an easy way
for people to fi nd and organize dinners online (Figure 1-1).

NerdDinner enables registered users to create, edit and delete dinners. It enforces a consistent set
of validation and business rules across the application (Figure 1-2).
Figure 1-1
Chapter 1 is licensed under the terms of Creative Commons Attribution No Derivatives 3.0 license and may be redistributed
according to those terms with the following attribution: “Chapter 1 “NerdDinner” from Professional ASP.NET MVC 1.0
written by Rob Conery, Scott Hanselman, Phil Haack, Scott Guthrie published by Wrox (ISBN: 978-0-470-38461-9) may be
redistributed under the terms of Creative Commons Attribution No Derivatives 3.0 license. The original electronic copy is
available at The complete book Professional ASP.NET MVC 1.0 is copyright 2009 by
Wiley Publishing Inc and may not redistributed without permission.”
84619c01.indd List184619c01.indd List1 3/31/09 5:25:44 AM3/31/09 5:25:44 AM
www.it-ebooks.info

×