professional the structure of a standard asp.net mvc ...€¦ · the difference between asp.net mvc...

30
ASP.NET MVC 1.0 Updates, source code, and Wrox technical support at www.wrox.com Professional ASP.NET MVC 1.0 Rob Conery, Scott Hanselman, Phil Haack, Scott Guthrie Wrox Programmer to Programmer TM Includes Scott Guthrie’s NerdDinner.com ASP.NET MVC Walkthrough

Upload: others

Post on 19-Jun-2020

17 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Professional The structure of a standard ASP.NET MVC ...€¦ · The difference between ASP.NET MVC and ASP.NET Web Forms and how to share data between the two How to secure your

Professional

ASP.NET MVC 1.0

www.wrox.com

$49.99 USA$59.99 CAN

Wrox Professional guides are planned and written by working programmers to meet the real-world needs of programmers, developers, and IT professionals. Focused and relevant, they address the issues technology professionals face every day. They provide examples, practical solutions, and expert education in new technologies, all designed to help programmers do a better job.

Recommended Computer Book

Categories

Web Development

ASP.NET/C#

ISBN: 978-0-470-38461-9

The ASP.NET MVC framework is designed from the ground up with certain core principles in mind—extensibility, testability, and separation of concerns. The framework adds various conventions into the mix to help drive developers into the “Pit of Success,” providing for a streamlined development experience that fits the way the web works.

For developers who like to peel away layers of abstraction and get their hands closer to the metal, the ASP.NET MVC framework might be for you. For developers who are extremely particular about how their frameworks should be put together, ASP.NET MVC is also extremely extensible, allowing nearly any part of it to be customized or even swapped out entirely in favor of something that fits the developer’s own tastes.

Written by members of the ASP.NET team, expert Scott Guthrie starts you out with an end-to-end walk-through, showing you how to build an application. You can even share Scott Guthrie’s NerdDinner.com chapter with your friends at http://tinyurl.com/aspnetmvc. You’ll then delve into basic concepts and the history of the Model-View-Controller (MVC), and quickly transition to learning how the ASP.NET MVC pattern implements those concepts.

You’ll explore controllers and views and examine the roles that AJAX and URLs play in your applications while the book demonstrates the myriad ways in which you can extend ASP.NET MVC. As you go through the book, you’ll come to understand the mind-shift that is required when making the change from traditional ASP.NET Web Forms development to ASP.NET MVC and the many benefits that exist once that change is made.

What you will learn from this book● The various toolsets and technologies that complement MVC, such as SubSonic,

LINQ, jQuery, and REST● The structure of a standard ASP.NET MVC application● Advanced routing strategies as well as advanced techniques for extending the framework● The difference between ASP.NET MVC and ASP.NET Web Forms and how to share data between the two● How to secure your ASP.NET MVC application

Who this book is forThis book is for ASP.NET developers who want to employ separation of concerns, extensibility, and control over markup whenbuilding web applications. A firm understanding of ASP.NET development using C# is necessary.

Enhance Your KnowledgeAdvance Your Career

AS

P.NET M

VC

1.0

ConeryHanselman

HaackGuthrie

Professional

spine=.912"

Updates, source code, and Wrox technical support at www.wrox.com

Professional

ASP.NET MVC 1.0

Rob Conery, Scott Hanselman, Phil Haack, Scott Guthrie

Wrox Programmer to Programmer TMWrox Programmer to Programmer TM

Includes Scott Guthrie’s NerdDinner.com

ASP.NET MVC Walkthrough

Page 2: Professional The structure of a standard ASP.NET MVC ...€¦ · The difference between ASP.NET MVC and ASP.NET Web Forms and how to share data between the two How to secure your

Professional

ASP.NET MVC 1.0

Enhance Your KnowledgeAdvance Your Career

ASP.NET MVC 1.0 Website ProgrammingProblem - Design - Solution978-0-470-41095-0A 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.0978-0-470-38461-9Professional 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 AJAX978-0-470-39217-1Discover 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 VB978-0-470-47826-4Updated 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.0978-0-470-43399-7Beginning 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 VB978-0-470-18759-3Beginning 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™

InteractTake an active role online by participating in our P2P forums

Wrox Online LibraryHundreds 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 DemandPurchase individual book chapters in pdf format

Join the CommunitySign up for our free monthly newsletter at newsletter.wrox.com

BrowseReady 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 [email protected]

Page 3: Professional The structure of a standard ASP.NET MVC ...€¦ · The difference between ASP.NET MVC and ASP.NET Web Forms and how to share data between the two How to secure your

Professional ASP.NET MVC 1.0

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xviiChapter 1: NerdDinner . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1Chapter 2: Model-View-Controller and ASP.NET . . . . . . . . . . . . . . . . . . . . . . 165Chapter 3: ASP.NET > ASP.NET MVC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 175Chapter 4: Routes and URLs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197Chapter 5: Controllers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 225Chapter 6: Views . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 251Chapter 7: AJAX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277Chapter 8: Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305Chapter 9: Securing Your Application . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325Chapter 10: Test Driven Development with ASP.NET MVC . . . . . . . . . . . . . . 349Chapter 11: Testable Design Patterns . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367Chapter 12: Best of Both Worlds: Web Forms and MVC Together . . . . . . . . 393Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 421

84619book.indb Listi84619book.indb Listi 3/30/09 2:56:51 PM3/30/09 2:56:51 PM

Page 4: Professional The structure of a standard ASP.NET MVC ...€¦ · The difference between ASP.NET MVC and ASP.NET Web Forms and how to share data between the two How to secure your

84619book.indb Listii84619book.indb Listii 3/30/09 2:56:51 PM3/30/09 2:56:51 PM

Page 5: Professional The structure of a standard ASP.NET MVC ...€¦ · The difference between ASP.NET MVC and ASP.NET Web Forms and how to share data between the two How to secure your

Professional

ASP.NET MVC 1.0

Rob ConeryScott GuthriePhil Haack

Scott Hanselman

84619book.indb Listiii84619book.indb Listiii 3/30/09 2:56:51 PM3/30/09 2:56:51 PM

Page 6: Professional The structure of a standard ASP.NET MVC ...€¦ · The difference between ASP.NET MVC and ASP.NET Web Forms and how to share data between the two How to secure your

Professional ASP.NET MVC 1.0Published byWiley Publishing, Inc.10475 Crosspoint BoulevardIndianapolis, IN 46256www.wiley.com.

Copyright © 2009 by Wiley Publishing, Inc., Indianapolis, IndianaPublished simultaneously in CanadaISBN: 978-0-470-38461-9Manufactured 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

Page 7: Professional The structure of a standard ASP.NET MVC ...€¦ · The difference between ASP.NET MVC and ASP.NET Web Forms and how to share data between the two How to secure your

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

Page 8: Professional The structure of a standard ASP.NET MVC ...€¦ · The difference between ASP.NET MVC and ASP.NET Web Forms and how to share data between the two How to secure your

About the AuthorsRob 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, http://haacked.com. 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

Page 9: Professional The structure of a standard ASP.NET MVC ...€¦ · The difference between ASP.NET MVC and ASP.NET Web Forms and how to share data between the two How to secure your

Associate PublisherJim Minatel

Development EditorMaureen Spears

Technical EditorsLevi BroderickDarren Kindberg

Production EditorKathleen Wisor

Copy EditorFoxxe Editorial Services

Editorial ManagerMary Beth Wakefi eld

Production ManagerTim Tate

Vice President and Executive Group PublisherRichard Swadley

Vice President and Executive PublisherBarry Pruett

Project Coordinator, CoverLynsey Stanford

CompositorCraig Woods, Happenstance Type-O-Rama

ProofreaderNancy C. Hanger, Windhaven

IndexerJ&J Indexing

Credits

84619book.indb Listvii84619book.indb Listvii 3/30/09 2:56:52 PM3/30/09 2:56:52 PM

Page 10: Professional The structure of a standard ASP.NET MVC ...€¦ · The difference between ASP.NET MVC and ASP.NET Web Forms and how to share data between the two How to secure your

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

Page 11: Professional The structure of a standard ASP.NET MVC ...€¦ · The difference between ASP.NET MVC and ASP.NET Web Forms and how to share data between the two How to secure your

Contents

Introduction xvii

NerdDinner Chapter 1: 1

File ➪ New Project 5Examining the NerdDinner Directory Structure 7Running the NerdDinner Application 9Testing the NerdDinner Application 12

Creating the Database 13Creating a New SQL Server Express Database 14Creating Tables within Our Database 15Setting Up a Foreign Key Relationship Between Tables 18Adding Data to Our Tables 20

Building the Model 20LINQ to SQL 21Adding LINQ to SQL Classes to Our Project 21Creating Data Model Classes with LINQ to SQL 22NerdDinnerDataContext Class 25Creating a DinnerRepository Class 26Retrieving, Updating, Inserting, and Deleting Using the DinnerRepository Class 28Integrating Validation and Business Rule Logic with Model Classes 30

Controllers and Views 34Adding a DinnersController Controller 35Adding Index and Details Action Methods to the DinnersController Class 36Understanding ASP.NET MVC Routing 37Using the DinnerRepository from Our DinnersController 39Using Views with Our Controller 40Implementing the “NotFound” View Template 42Implementing the “Details” View Template 44Implementing the “Index” View Template 49Convention-Based Naming and the \Views Directory Structure 54

Create, Update, Delete Form Scenarios 56URLs Handled by DinnersController 56Implementing the HTTP-GET Edit Action Method 57Html.BeginForm and Html.TextBox Html Helper Methods 61Implementing 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

Page 12: Professional The structure of a standard ASP.NET MVC ...€¦ · The difference between ASP.NET MVC and ASP.NET Web Forms and how to share data between the two How to secure your

x

Contents

Handling Edit Errors 66Understanding ModelState and the Validation HTML Helper Methods 68Using a AddRuleViolations Helper Method 70Complete Edit Action Method Implementations 71Implementing the HTTP-GET Create Action Method 72Implementing the HTTP-POST Create Action Method 74Implementing the HTTP-GET Delete Action Method 78Implementing the HTTP-POST Delete Action Method 80Model Binding Security 82CRUD Wrap-Up 83

ViewData and ViewModel 86Passing Data from Controllers to View Templates 86Using the ViewData Dictionary 87Using a ViewModel Pattern 89Custom-Shaped ViewModel Classes 92

Partials and Master Pages 92Revisiting Our Edit and Create View Templates 92Using Partial View Templates 93Using Partial View Templates to Clarify Code 97Master Pages 98

Paging Support 101Index() Action Method Recap 102Understanding IQueryable<T> 102Adding a “page” Value to the URL 103Adding Page Navigation UI 106

Authentication and Authorization 110Understanding Authentication and Authorization 110Forms Authentication and the AccountController 111Authorizing the /Dinners/Create URL Using the [Authorize] Filter 114Using the User.Identity.Name Property When Creating Dinners 116Using the User.Identity.Name Property When Editing Dinners 116Showing/Hiding Edit and Delete Links 118

AJAX Enabling RSVPs Accepts 119Indicating Whether the User Is RSVP’ed 120Implementing the Register Action Method 122Calling the Register Action Method Using AJAX 123Adding a jQuery Animation 125Cleanup — Refactor out a RSVP Partial View 127

Integrating an AJAX Map 127Creating a Map Partial View 127Creating a Map.js Utility Library 129Integrating 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

Page 13: Professional The structure of a standard ASP.NET MVC ...€¦ · The difference between ASP.NET MVC and ASP.NET Web Forms and how to share data between the two How to secure your

xi

Contents

Integrating the Map with the Details View 135Implementing Location Search in Our Database and Repository 136Implementing a JSON-Based AJAX Search Action Method 140Calling the JSON-Based AJAX Method Using jQuery 141

Unit Testing 145Why Unit Test? 145NerdDinner.Tests Project 146Creating Unit Tests for Our Dinner Model Class 147Running Tests 149Creating DinnersController Unit Tests 150Dependency Injection 152Extracting an IDinnerRepository Interface 152Updating DinnersController to Support Constructor Injection 154Creating the FakeDinnerRepository Class 154Using the FakeDinnerRepository with Unit Tests 157Creating Edit Action Unit Tests 159Mocking the User.Identity.Name Property 160Testing UpdateModel() Scenarios 162Testing Wrap-Up 163

NerdDinner Wrap-Up 164

Model-View-Controller and ASP.NET 16Chapter 2: 5

What Is Model-View-Controller? 165MVC on the Web Today 167

Ruby on Rails 168Django and Python 169Spring, Struts, and Java 169Zend Framework and PHP 170MonoRail 170

ASP.NET MVC: The New Kid on the Block 170Serving Methods, Not Files 171Is This Web Forms 4.0? 171Why Not Web Forms? 172Cost/Benefi t of Web Forms 172Should You Fear ASP.NET MVC? 173

Summary 174

ASP.NET > ASP.NET MVC 17Chapter 3: 5

Abstraction: What Web Forms Does Well 175A Basic Web Forms Application 176The Importance of Events 180

84619book.indb Listxi84619book.indb Listxi 3/30/09 2:09:08 PM3/30/09 2:09:08 PM

Page 14: Professional The structure of a standard ASP.NET MVC ...€¦ · The difference between ASP.NET MVC and ASP.NET Web Forms and how to share data between the two How to secure your

xii

Contents

The Leak: Where Web Forms Doesn’t Exactly Fit 181ViewState 183Controlling Your Angle Brackets 183Client IDs 183Testing 183

Back to Basics: ASP.NET MVC Believes . . . 184Orchestration versus Composing 184Separation of Concerns: What It Means 184Approaches to Maintainability 185

Caring About Testability 186Common Reactions to ASP.NET MVC 187

This Looks Like Classic ASP from 1999! 187Who Moved My “<asp:Cheese runat=“server”> 187Yet Another Web Framework 188

Why “(ASP.NET > ASP.NET MVC) == True” 188Convention over Confi guration 190Your First, er, Third, Request 194The Request Lifecycle 196

Summary 196

Routes and URLs 19Chapter 4: 7

Introduction to Routing 198Compared to URL Rewriting 199Defi ning Routes 199Named Routes 206Catch-All Parameter 206StopRoutingHandler 208Under the Hood: How Routes Generate URLs 209

Under the Hood: How Routes Tie Your URL to an Action 216The High-Level Request Routing Pipeline 217Route Matching 217

Advanced Routing with Custom Constraints 217Route Extensibility 218Using Routing with Web Forms 222Summary 224

Controllers 22Chapter 5: 5

History of the Controller 225Defi ning the Controller: The IController Interface 227The ControllerBase Abstract Base Class 229The 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

Page 15: Professional The structure of a standard ASP.NET MVC ...€¦ · The difference between ASP.NET MVC and ASP.NET Web Forms and how to share data between the two How to secure your

xiii

Contents

The ActionResult 233Action Result Types 235Action Result Helper Methods 238Implicit Action Results 239

Action Invoker 240How an Action Is Mapped to a Method 241Mapping Parameters 243Invoking Actions 244Passing Data to Actions: The Model Binders 244A Word About User Input 248

Summary 249

Views 25Chapter 6: 1

What a View Does 251What a View Shouldn’t Do 253Specifying a View 253Strongly Typed Views 255HTML Helper Methods 257

HtmlHelper Class and Extension Methods 257Using the HTML Helpers 258

The View Engine 266Confi guring a View Engine 267Selecting a View Engine 267Finding a View 268The View Itself 269Alternative View Engines 269

New View Engine or New ActionResult? 275Summary 275

AJAX 27Chapter 7: 7

When AJAX Is Cool 278When It’s Not 278AJAX Examples 280

Handling Disabled Scripting 280Using Partials for Rendering 284Some Things You May Not Know About Microsoft ASP.NET AJAX 288Updating an HTML Element When Submitting a Form 290The Auto-Complete Text Box 292Implementing Auto-Complete with Microsoft ASP.NET AJAX 292Filtering Data with a Selectbox 295

84619book.indb Listxiii84619book.indb Listxiii 3/30/09 2:09:09 PM3/30/09 2:09:09 PM

Page 16: Professional The structure of a standard ASP.NET MVC ...€¦ · The difference between ASP.NET MVC and ASP.NET Web Forms and how to share data between the two How to secure your

xiv

Contents

The Modal Popup with jQuery 296The Modal Popup Code 297The Rating Control 299

Summary 303

Filters 30Chapter 8: 5

Filters Included with ASP.NET MVC 305Authorize 306OutputCache 308Exception Filter 310Custom Filters 311

Writing a Custom Action Filter 316Writing a Custom Authorization Filter 317Writing a Custom Exception Filter 319Filter Ordering 320Filter Naming 321Summary 323

Securing Your Application 32Chapter 9: 5

This Is a War 327Knowing Your Enemy’s Mind 327

Weapons 331Spam 331Case Study: Profi ting from Evil with the Srizbi and Storm Botnets 332Digital Stealth Ninja Network 333

Threat: Cross-Site Scripting (XSS) 334Passive Injection 334Active Injection 336Preventing XSS 338Html.AttributeEncode and Url.Encode 338

Threat: Cross-Site Request Forgery 339Preventing CSRF Attacks 342

Threat: Cookie Stealing 343Preventing Cookie Theft with HttpOnly 344Keeping Your Pants Up: Proper Error Reporting and the Stack Trace 345Securing Your Controllers, Not Your Routes 345

Using [Authorize] to Lock Down Your Action or Controller 346Using [NonAction] to Protect Public Methods 346Whitelist Form Binding 347Summary: It’s Up to You 348

84619book.indb Listxiv84619book.indb Listxiv 3/30/09 2:09:09 PM3/30/09 2:09:09 PM

Page 17: Professional The structure of a standard ASP.NET MVC ...€¦ · The difference between ASP.NET MVC and ASP.NET Web Forms and how to share data between the two How to secure your

xv

Contents

Test Driven Development with ASP.NET MVC 34Chapter 10: 9

A Brief Introduction to TDD 350What Does TDD Look Like? 350Writing Good Unit Tests 353What Are Some Benefi ts of Writing Tests? 357How Do I Get Started? 357

Applying TDD to ASP.NET MVC 357Testing Routes 358Testing Controllers 360Redirecting to Another Action 360Testing View Helpers 362Testing Views 364

Summary 365

Testable Design Patterns 36Chapter 11: 7

Why You Should Care About Testability 368Big Design Up Front (BDUF) 368Agile Software Development 369

You Want to Write Testable Code 370Using Tests to Prove You’re Done 371Designing Your Application for Testability 371

Future-Proofi ng Your Application with Interfaces 371The Single Responsibility Principle 373Avoid Using Singletons and Static Methods 373

Testable Data Access 376Creating the Model 377The Repository Pattern in Detail 379

Implementing Business Logic with the Service Layer 383Services Gone Wild 385Partial Solution: Setting Controller Dependencies Manually 386

Summary 392

Best of Both Worlds: Web Forms and MVC Together 39Chapter 12: 3

How Is It Possible? 393Including MVC in Existing Web Forms Applications 394

Step 1: Referencing the Required Libraries 394Step 2: Creating the Necessary Directories 395Step 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

Page 18: Professional The structure of a standard ASP.NET MVC ...€¦ · The difference between ASP.NET MVC and ASP.NET Web Forms and how to share data between the two How to secure your

xvi

Contents

Adding Web Forms to an Existing ASP.NET MVC Application 398The Easy Part: Do Nothing 399When/Home/Isn’t/Home/ 401Using System.Web.Routing to Route to Web Forms 401

Sharing Data Between Web Forms and MVC 402Using HTTP POST 402Using the ASP.NET Session 403Using Cross-Page Posting 404Using TempData 406

Migrating from Web Forms to MVC 407Step 1: Create an Empty ASP.NET MVC Project with a Test Project 407Step 2: Implement the Structure 408Step 3: Add Images and Styling 410Step 4: Setting Up Routing and Controllers 411Step 5: Replacing Complex Server Controls 415Step 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

Page 19: Professional The structure of a standard ASP.NET MVC ...€¦ · The difference between ASP.NET MVC and ASP.NET Web Forms and how to share data between the two How to secure your

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 ForThis 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

Page 20: Professional The structure of a standard ASP.NET MVC ...€¦ · The difference between ASP.NET MVC and ASP.NET Web Forms and how to share data between the two How to secure your

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 StructuredThis 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

Page 21: Professional The structure of a standard ASP.NET MVC ...€¦ · The difference between ASP.NET MVC and ASP.NET Web Forms and how to share data between the two How to secure your

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 BookTo 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

ConventionsTo 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

Page 22: Professional The structure of a standard ASP.NET MVC ...€¦ · The difference between ASP.NET MVC and ASP.NET Web Forms and how to share data between the two How to secure your

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 CodeThe main nerddinner.com code download is hosted at codeplex and the most up-to-date code will always be available at http://www.codeplex.com/nerddinner. 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

Page 23: Professional The structure of a standard ASP.NET MVC ...€¦ · The difference between ASP.NET MVC and ASP.NET Web Forms and how to share data between the two How to secure your

Introduction

xxi

ErrataWe 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.comFor 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 http://p2p.wrox.com 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

Page 24: Professional The structure of a standard ASP.NET MVC ...€¦ · The difference between ASP.NET MVC and ASP.NET Web Forms and how to share data between the two How to secure your

84619flast.indd Listxxii84619flast.indd Listxxii 3/31/09 5:34:35 AM3/31/09 5:34:35 AM

Page 25: Professional The structure of a standard ASP.NET MVC ...€¦ · The difference between ASP.NET MVC and ASP.NET Web Forms and how to share data between the two How to secure your

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 http://tinyurl.com/aspnetmvc. 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

Page 26: Professional The structure of a standard ASP.NET MVC ...€¦ · The difference between ASP.NET MVC and ASP.NET Web Forms and how to share data between the two How to secure your

2

Chapter 1: NerdDinner

Figure 1-2

Visitors to the site can search to fi nd upcoming dinners being held near them (Figure 1-3):

Figure 1-3

84619c01.indd List284619c01.indd List2 3/31/09 5:25:45 AM3/31/09 5:25:45 AM

Page 27: Professional The structure of a standard ASP.NET MVC ...€¦ · The difference between ASP.NET MVC and ASP.NET Web Forms and how to share data between the two How to secure your

3

Chapter 1: NerdDinner

Clicking a dinner will take them to a details page where they can learn more about it (Figure 1-4):

Figure 1-4

If they are interested in attending the dinner they can log in or register on the site (Figure 1-5):

Figure 1-5

They can then easily RSVP to attend the event (Figures 1-6 and 1-7):

84619c01.indd List384619c01.indd List3 3/31/09 5:25:46 AM3/31/09 5:25:46 AM

Page 28: Professional The structure of a standard ASP.NET MVC ...€¦ · The difference between ASP.NET MVC and ASP.NET Web Forms and how to share data between the two How to secure your

4

Chapter 1: NerdDinner

Figure 1-6

Figure 1-7

84619c01.indd List484619c01.indd List4 3/31/09 5:25:46 AM3/31/09 5:25:46 AM

Page 29: Professional The structure of a standard ASP.NET MVC ...€¦ · The difference between ASP.NET MVC and ASP.NET Web Forms and how to share data between the two How to secure your

5

Chapter 1: NerdDinner

We are going to begin implementing the NerdDinner application by using the File ➪ New Project com-mand within Visual Studio to create a brand new ASP.NET MVC project. We’ll then incrementally add functionality and features. Along the way we’ll cover how to create a database, build a model with business rule validations, implement data listing/details UI, provide CRUD (Create, Update, Delete) form entry sup-port, implement effi cient data paging, reuse the UI using master pages and partials, secure the application using authentication and authorization, use AJAX to deliver dynamic updates and interactive map support, and implement automated unit testing.

You can build your own copy of NerdDinner from scratch by completing each step we walk through in this chapter. Alternatively, you can download a completed version of the source code here: http://tinyurl.com/aspnetmvc.

You can use either Visual Studio 2008 or the free Visual Web Developer 2008 Express to build the application. You can use either SQL Server or the free SQL Server Express to host the database.

You can install ASP.NET MVC, Visual Web Developer 2008, and SQL Server Express using the Microsoft Web Platform Installer available at www.microsoft.com/web/downloads.

File ➪ New ProjectWe’ll begin our NerdDinner application by selecting the File ➪ New Project menu item within Visual Studio 2008 or the free Visual Web Developer 2008 Express.

This will bring up the New Project dialog. To create a new ASP.NET MVC application, we’ll select the Web node on the left side of the dialog and then choose the ASP.NET MVC Web Application project template on the right (Figure 1-8):

Figure 1-8

We’ll name the new project NerdDinner and then click the OK button to create it.

When we click OK, Visual Studio will bring up an additional dialog that prompts us to optionally create a unit test project for the new application as well (Figure 1-9). This unit test project enables us to create auto-mated tests that verify the functionality and behavior of our application (something we’ll cover later in this tutorial).

84619c01.indd List584619c01.indd List5 3/31/09 5:25:46 AM3/31/09 5:25:46 AM

Page 30: Professional The structure of a standard ASP.NET MVC ...€¦ · The difference between ASP.NET MVC and ASP.NET Web Forms and how to share data between the two How to secure your

6

Chapter 1: NerdDinner

Figure 1-9

The Test framework drop-down in Figure 1-9 is populated with all available ASP.NET MVC unit test project templates installed on the machine. Versions can be downloaded for NUnit, MBUnit, and XUnit. The built-in Visual Studio Unit Test Framework is also supported.

The Visual Studio Unit Test Framework is only available with Visual Studio 2008 Professional and higher versions). If you are using VS 2008 Standard Edition or Visual Web Developer 2008 Express, you will need to download and install the NUnit, MBUnit, or XUnit extensions for ASP.NET MVC in order for this dialog to be shown. The dialog will not display if there aren’t any test frameworks installed.

We’ll use the default NerdDinner.Tests name for the test project we create, and use the Visual Studio Unit Test Framework option. When we click the OK button, Visual Studio will create a solution for us with two projects in it — one for our web application and one for our unit tests (Figure 1-10):

Figure 1-10

84619c01.indd List684619c01.indd List6 3/31/09 5:25:46 AM3/31/09 5:25:46 AM