Pro ASP.NET MVC 4 - link.springer.com3A978-1-4302-4237-6%2F… · Part 1: Introducing ASP.NET MVC 4...

22
Pro ASP.NET MVC 4 Adam Freeman Apress

Transcript of Pro ASP.NET MVC 4 - link.springer.com3A978-1-4302-4237-6%2F… · Part 1: Introducing ASP.NET MVC 4...

Page 1: Pro ASP.NET MVC 4 - link.springer.com3A978-1-4302-4237-6%2F… · Part 1: Introducing ASP.NET MVC 4 .....1 Chapter 1: What’s the Big Idea? ..... 3 Chapter 2: Your First MVC Application

Pro ASP.NET MVC 4

� � ����

Adam Freeman

Apress

Page 2: Pro ASP.NET MVC 4 - link.springer.com3A978-1-4302-4237-6%2F… · Part 1: Introducing ASP.NET MVC 4 .....1 Chapter 1: What’s the Big Idea? ..... 3 Chapter 2: Your First MVC Application

Pro ASP.NET MVC 4

Copyright © 2012 by Adam Freeman

This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Exempted from this legal reservation are brief excerpts in connection with reviews or scholarly analysis or material supplied specifically for the purpose of being entered and executed on a computer system, for exclusive use by the purchaser of the work. Duplication of this publication or parts thereof is permitted only under the provisions of the Copyright Law of the Publisher's location, in its current version, and permission for use must always be obtained from Springer. Permissions for use may be obtained through RightsLink at the Copyright Clearance Center. Violations are liable to prosecution under the respective Copyright Law.

ISBN 978-1-4302-4236-9

ISBN 978-1-4302-4237-6

Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark.

The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights.

While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein.

President and Publisher: Paul Manning Lead Editor: Ewan Buckingham Technical Reviewer: Fabio Claudio Ferracchiati Editorial Board: Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell, Louise Corrigan, Morgan Ertel,

Jonathan Gennick, Jonathan Hassell, Robert Hutchinson, Michelle Lowman, James Markham, Matthew Moodie, Jeff Olson, Jeffrey Pepper, Douglas Pundick, Ben Renow-Clarke, Dominic Shakeshaft, Gwenan Spearing, Matt Wade, Tom Welsh

Coordinating Editor: Christine Ricketts Copy Editors: Laura Lawrie and Kimberly Burton-Weisman Compositor: Christine Ricketts Indexer: SPi Global Artist: SPi Global Cover Designer: Anna Ishchenko

Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail [email protected], or visit www.springeronline.com. Apress Media, LLC is a California LLC and the sole member (owner) is Springer Science + Business Media Finance Inc (SSBM Finance Inc). SSBM Finance Inc is a Delaware corporation.

For information on translations, please e-mail [email protected], or visit www.apress.com.

Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Special Bulk Sales–eBook Licensing web page at www.apress.com/bulk-sales.

Any source code or other supplementary materials referenced by the author in this text is available to readers at www.apress.com. For detailed information about how to locate your book’s source code, go to www.apress.com/source-code/.

(eBook)

Page 3: Pro ASP.NET MVC 4 - link.springer.com3A978-1-4302-4237-6%2F… · Part 1: Introducing ASP.NET MVC 4 .....1 Chapter 1: What’s the Big Idea? ..... 3 Chapter 2: Your First MVC Application

Dedicated to my lovely wife, Jacqui Griffyth.

Page 4: Pro ASP.NET MVC 4 - link.springer.com3A978-1-4302-4237-6%2F… · Part 1: Introducing ASP.NET MVC 4 .....1 Chapter 1: What’s the Big Idea? ..... 3 Chapter 2: Your First MVC Application

v

Contents at a Glance

■ Contents ................................................................................................................... vii

■ About the Author ..................................................................................................... xxi

■ About the Technical Reviewer ................................................................................ xxii

■ Acknowledgments ................................................................................................. xxiii

■ Part 1: Introducing ASP.NET MVC 4 .............................................................................1

■ Chapter 1: What’s the Big Idea? ................................................................................. 3

■ Chapter 2: Your First MVC Application ..................................................................... 15

■ Chapter 3: The MVC Pattern ..................................................................................... 47

■ Chapter 4: Essential Language Features .................................................................. 73

■ Chapter 5: Working with Razor .............................................................................. 101

■ Chapter 6: Essential Tools for MVC ........................................................................ 125

■ Chapter 7: SportsStore—A Real Application .......................................................... 161

■ Chapter 8: SportsStore: Navigation ........................................................................ 201

■ Chapter 9: SportsStore: Completing the Cart ......................................................... 231

■ Chapter 10: SportsStore: Administration ............................................................... 255

■ Chapter 11: SportsStore: Security & Finishing Touches ........................................ 283

■ Part 2: ASP.NET MVC 4 in Detail ............................................................................. 301

■ Chapter 12: Overview of MVC Projects ................................................................... 303

■ Chapter 13: URL Routing ........................................................................................ 323

Page 5: Pro ASP.NET MVC 4 - link.springer.com3A978-1-4302-4237-6%2F… · Part 1: Introducing ASP.NET MVC 4 .....1 Chapter 1: What’s the Big Idea? ..... 3 Chapter 2: Your First MVC Application

■ CONTENTS AT A GLANCE

vi

■ Chapter 14: Advanced Routing Features ................................................................ 363

■ Chapter 15: Controllers and Actions ...................................................................... 391

■ Chapter 16: Filters .................................................................................................. 419

■ Chapter 17: Controller Extensibility ....................................................................... 455

■ Chapter 18: Views .................................................................................................. 485

■ Chapter 19: Helper Methods ................................................................................... 511

■ Chapter 20: Templated Helper Methods ................................................................. 541

■ Chapter 21: URL and Ajax Helper Methods ............................................................. 569

■ Chapter 22: Model Binding ..................................................................................... 599

■ Chapter 23: Model Validation ................................................................................. 629

■ Chapter 24: Bundles and Display Modes ................................................................ 657

■ Chapter 25: Web API ............................................................................................... 679

■ Chapter 26: Deployment ......................................................................................... 699

■ Index ....................................................................................................................... 717

Page 6: Pro ASP.NET MVC 4 - link.springer.com3A978-1-4302-4237-6%2F… · Part 1: Introducing ASP.NET MVC 4 .....1 Chapter 1: What’s the Big Idea? ..... 3 Chapter 2: Your First MVC Application

vii

Contents

■ Contents at a Glance .................................................................................................. v

■ About the Author ..................................................................................................... xxi

■ About the Technical Reviewer ................................................................................ xxii

■ Acknowledgments ............................................................................................... xxiii

■ Part 1: Introducing ASP.NET MVC 4 ............................................................................ 1

■ Chapter 1: What’s the Big Idea? ................................................................................. 3

A Brief History of Web Development ........................................................................... 3 Traditional ASP.NET Web Forms ........................................................................................ 4 What Is Wrong with ASP.NET Web Forms? ........................................................................ 5

Web Development Today ............................................................................................ 6 Web Standards and REST .................................................................................................. 6 Agile and Test-Driven Development .................................................................................. 7 Ruby on Rails ..................................................................................................................... 7 Sinatra ............................................................................................................................... 8 Node.js ............................................................................................................................... 8

Key Benefits of ASP.NET MVC ..................................................................................... 9 MVC Architecture ............................................................................................................... 9 Extensibility ....................................................................................................................... 9 Tight Control over HTML and HTTP .................................................................................. 10 Testability ........................................................................................................................ 10 Powerful Routing System ................................................................................................ 10 Built on the Best Parts of the ASP.NET Platform .............................................................. 11 Modern API ...................................................................................................................... 11 ASP.NET MVC Is Open Source .......................................................................................... 11

Page 7: Pro ASP.NET MVC 4 - link.springer.com3A978-1-4302-4237-6%2F… · Part 1: Introducing ASP.NET MVC 4 .....1 Chapter 1: What’s the Big Idea? ..... 3 Chapter 2: Your First MVC Application

■ CONTENTS

viii

Who Should Use ASP.NET MVC? ............................................................................... 12 Comparisons with ASP.NET Web Forms .......................................................................... 12 Migrating from Web Forms to MVC .................................................................................. 12 Comparisons with Ruby on Rails ..................................................................................... 13 Comparisons with MonoRail ............................................................................................ 13

What’s New in ASP.NET MVC 4? ............................................................................... 13 Summary .................................................................................................................. 13

■ Chapter 2: Your First MVC Application ..................................................................... 15

Preparing the Workstation ....................................................................................... 15 Creating a New ASP.NET MVC Project ...................................................................... 16

Adding the First Controller ............................................................................................... 19 Understanding Routes ..................................................................................................... 21

Rendering Web Pages ............................................................................................... 22 Creating and Rendering a View ....................................................................................... 22 Adding Dynamic Output ................................................................................................... 25

Creating a Simple Data-Entry Application ................................................................ 27 Setting the Scene ............................................................................................................ 27 Designing a Data Model ................................................................................................... 28 Linking Action Methods ................................................................................................... 29 Building the Form ............................................................................................................ 32 Handling Forms ................................................................................................................ 35 Adding Validation ............................................................................................................. 38 Completing the Example .................................................................................................. 44

Summary .................................................................................................................. 45 ■ Chapter 3: The MVC Pattern ..................................................................................... 47

The History of MVC ................................................................................................... 47 Understanding the MVC Pattern ............................................................................... 47

Understanding the Domain Model ................................................................................... 48 The ASP.NET Implementation of MVC .............................................................................. 49 Comparing MVC to Other Patterns ................................................................................... 49

Applying Domain-Driven Development ..................................................................... 53 Modeling an Example Domain ......................................................................................... 53 Ubiquitous Language ....................................................................................................... 54 Aggregates and Simplification ......................................................................................... 54 Defining Repositories ....................................................................................................... 56

Page 8: Pro ASP.NET MVC 4 - link.springer.com3A978-1-4302-4237-6%2F… · Part 1: Introducing ASP.NET MVC 4 .....1 Chapter 1: What’s the Big Idea? ..... 3 Chapter 2: Your First MVC Application

CONTENTS ■

ix

Building Loosely Coupled Components..................................................................... 57 Using Dependency Injection ............................................................................................ 58 An MVC-Specific DI Example ........................................................................................... 59 Using a Dependency Injection Container ......................................................................... 60

Getting Started with Automated Testing .................................................................. 62 Understanding Unit Testing ............................................................................................. 62 Understanding Integration Testing .................................................................................. 70

Summary .................................................................................................................. 71 ■ Chapter 4: Essential Language Features .................................................................. 73

Creating the Example Project ................................................................................... 73 Using Automatically Implemented Properties .......................................................... 74 Using Object and Collection Initializers .................................................................... 78 Using Extension Methods ......................................................................................... 80

Applying Extension Methods to an Interface ................................................................... 82 Creating Filtering Extension Methods .............................................................................. 84

Using Lambda Expressions ....................................................................................... 86 Using Automatic Type Inference ............................................................................... 89 Using Anonymous Types .......................................................................................... 90 Performing Language Integrated Queries ................................................................ 91

Understanding Deferred LINQ Queries ............................................................................. 95 Using Async Methods ............................................................................................... 97

Applying the async and await Keywords ......................................................................... 99 Summary ................................................................................................................ 100

■ Chapter 5: Working with Razor .............................................................................. 101

Creating the Example Project ................................................................................. 101 Defining the Model ......................................................................................................... 101 Defining the Controller ................................................................................................... 102 Creating the View ........................................................................................................... 103

Working with the Model Object .............................................................................. 104 Working with Layouts ............................................................................................. 106

Creating the Layout ........................................................................................................ 107 Applying a Layout .......................................................................................................... 108 Using a View Start File ................................................................................................... 109 Demonstrating Shared Layouts ..................................................................................... 110

Page 9: Pro ASP.NET MVC 4 - link.springer.com3A978-1-4302-4237-6%2F… · Part 1: Introducing ASP.NET MVC 4 .....1 Chapter 1: What’s the Big Idea? ..... 3 Chapter 2: Your First MVC Application

■ CONTENTS

x

Using Razor Expressions ........................................................................................ 114 Inserting Data Values ..................................................................................................... 115 Setting Attribute Values ................................................................................................. 117 Using Conditional Statements ........................................................................................ 118 Enumerating Arrays and Collections .............................................................................. 121 Dealing with Namespaces ............................................................................................. 123

Summary ................................................................................................................ 124 ■ Chapter 6: Essential Tools for MVC ........................................................................ 125

Creating the Example Project ................................................................................. 126 Creating the Model Classes ........................................................................................... 126 Adding the Controller ..................................................................................................... 127 Adding the View ............................................................................................................. 128

Using Ninject .......................................................................................................... 129 Understanding the Problem ........................................................................................... 129 Adding Ninject to the Visual Studio Project ................................................................... 130 Getting Started with Ninject ........................................................................................... 131 Setting up MVC Dependency Injection ........................................................................... 133 Creating Chains of Dependency ..................................................................................... 136 Specifying Property and Constructor Parameter Values ................................................ 138 Using Conditional Binding .............................................................................................. 140

Unit Testing with Visual Studio .............................................................................. 141 Creating the Unit Test Project ........................................................................................ 142 Creating the Unit Tests .................................................................................................. 143 Running the Unit Tests (and Failing) .............................................................................. 147 Implementing the Feature ............................................................................................. 148 Testing and Fixing the Code .......................................................................................... 148

Using Moq ............................................................................................................... 150 Understanding the Problem ........................................................................................... 150 Adding Moq to the Visual Studio Project ........................................................................ 152 Adding a Mock Object to a Unit Test .............................................................................. 153 Creating a More Complex Mock Object .......................................................................... 156

Summary ................................................................................................................ 159 ■ Chapter 7: SportsStore—A Real Application .......................................................... 161

Getting Started ....................................................................................................... 162 Creating the Visual Studio Solution and Projects ........................................................... 162

Page 10: Pro ASP.NET MVC 4 - link.springer.com3A978-1-4302-4237-6%2F… · Part 1: Introducing ASP.NET MVC 4 .....1 Chapter 1: What’s the Big Idea? ..... 3 Chapter 2: Your First MVC Application

CONTENTS ■

xi

Adding References ......................................................................................................... 164 Setting Up the DI Container ........................................................................................... 165 Starting the Application ................................................................................................. 167

Starting the Domain Model ..................................................................................... 168 Creating an Abstract Repository .................................................................................... 169 Making a Mock Repository ............................................................................................ 169

Displaying a List of Products .................................................................................. 170 Adding a Controller ........................................................................................................ 170 Adding the View ............................................................................................................. 172 Setting the Default Route ............................................................................................... 173 Running the Application ................................................................................................. 174

Preparing a Database ............................................................................................. 175 Creating the Database ................................................................................................... 175 Defining the Database Schema ..................................................................................... 177 Adding Data to the Database ......................................................................................... 179 Creating the Entity Framework Context ......................................................................... 179 Creating the Product Repository .................................................................................... 181

Adding Pagination .................................................................................................. 183 Displaying Page Links .................................................................................................... 185 Improving the URLs ........................................................................................................ 193

Styling the Content ................................................................................................. 194 Defining Common Content in the Layout ....................................................................... 195 Adding CSS Styles ......................................................................................................... 196 Creating a Partial View .................................................................................................. 197

Summary ................................................................................................................ 199 ■ Chapter 8: SportsStore: Navigation ........................................................................ 201

Adding Navigation Controls .................................................................................... 201 Filtering the Product List................................................................................................ 201 Refining the URL Scheme .............................................................................................. 205 Building a Category Navigation Menu ............................................................................ 207 Correcting the Page Count ............................................................................................. 216

Building the Shopping Cart ..................................................................................... 219 Defining the Cart Entity .................................................................................................. 219 Adding the Add to Cart Buttons ..................................................................................... 223 Implementing the Cart Controller ................................................................................... 224

Page 11: Pro ASP.NET MVC 4 - link.springer.com3A978-1-4302-4237-6%2F… · Part 1: Introducing ASP.NET MVC 4 .....1 Chapter 1: What’s the Big Idea? ..... 3 Chapter 2: Your First MVC Application

■ CONTENTS

xii

Displaying the Contents of the Cart ............................................................................... 226 Summary ................................................................................................................ 230

■ Chapter 9: SportsStore: Completing the Cart ......................................................... 231

Using Model Binding ............................................................................................... 231 Creating a Custom Model Binder ................................................................................... 231

Completing the Cart ................................................................................................ 236 Removing Items from the Cart ....................................................................................... 236 Adding the Cart Summary .............................................................................................. 237

Submitting Orders .................................................................................................. 240 Extending the Domain Model ......................................................................................... 240 Adding the Checkout Process ........................................................................................ 241 Implementing the Order Processor ................................................................................ 244 Registering the Implementation .................................................................................... 247 Completing the Cart Controller ...................................................................................... 248 Displaying Validation Errors ........................................................................................... 252 Displaying a Summary Page .......................................................................................... 253

Summary ................................................................................................................ 254 ■ Chapter 10: SportsStore: Administration ............................................................... 255

Adding Catalog Management ................................................................................. 255 Creating a CRUD Controller ............................................................................................ 255 Creating a New Layout ................................................................................................... 258 Implementing the List View ........................................................................................... 260 Editing Products ............................................................................................................. 263 Creating New Products .................................................................................................. 277 Deleting Products .......................................................................................................... 279

Summary ................................................................................................................ 281 ■ Chapter 11: SportsStore: Security & Finishing Touches ........................................ 283

Securing the Administration Controller .................................................................. 283 Applying Authorization with Filters ................................................................................ 284 Creating the Authentication Provider ............................................................................. 286 Creating the Account Controller ..................................................................................... 288 Creating the View ........................................................................................................... 289

Image Uploads ........................................................................................................ 292 Extending the Database ................................................................................................. 293

Page 12: Pro ASP.NET MVC 4 - link.springer.com3A978-1-4302-4237-6%2F… · Part 1: Introducing ASP.NET MVC 4 .....1 Chapter 1: What’s the Big Idea? ..... 3 Chapter 2: Your First MVC Application

CONTENTS ■

xiii

Enhancing the Domain Model ........................................................................................ 294 Creating the Upload User Interface Elements ................................................................ 295 Saving Images to the Database ..................................................................................... 296 Implementing the GetImage Action Method .................................................................. 297 Displaying Product Images ............................................................................................ 299

Summary ................................................................................................................ 300 ■ Part 2: ASP.NET MVC 4 in Detail ............................................................................. 301

■ Chapter 12: Overview of MVC Projects ................................................................... 303

Working with Visual Studio MVC Projects .............................................................. 303 Understanding MVC Conventions ................................................................................... 308

Debugging MVC Applications ................................................................................. 310 Creating the Project ....................................................................................................... 310 Launching the Visual Studio Debugger .......................................................................... 312 Causing the Visual Studio Debugger to Break ............................................................... 314 Using Edit and Continue ................................................................................................. 319

Summary ................................................................................................................ 322 ■ Chapter 13: URL Routing ........................................................................................ 323

Creating the Example Project ................................................................................. 323 Introducing URL Patterns ....................................................................................... 326 Creating and Registering a Simple Route ............................................................... 327

Using the Simple Route ................................................................................................. 330 Defining Default Values .......................................................................................... 333 Using Static URL Segments .................................................................................... 336 Defining Custom Segment Variables ...................................................................... 340

Using Custom Variables as Action Method Parameters ................................................. 343 Defining Optional URL Segments ................................................................................... 344 Defining Variable-Length Routes ................................................................................... 347 Prioritizing Controllers by Namespaces ......................................................................... 349

Constraining Routes ............................................................................................... 353 Constraining a Route Using a Regular Expression ......................................................... 353 Constraining a Route to a Set of Specific Values ........................................................... 353 Constraining a Route Using HTTP Methods ................................................................... 354 Defining a Custom Constraint ........................................................................................ 355

Routing Requests for Disk Files ............................................................................. 357

Page 13: Pro ASP.NET MVC 4 - link.springer.com3A978-1-4302-4237-6%2F… · Part 1: Introducing ASP.NET MVC 4 .....1 Chapter 1: What’s the Big Idea? ..... 3 Chapter 2: Your First MVC Application

■ CONTENTS

xiv

Configuring the Application Server ................................................................................ 358 Defining Routes for Disk Files ........................................................................................ 360

Bypassing the Routing System ............................................................................... 361 Summary ................................................................................................................ 362

■ Chapter 14: Advanced Routing Features ................................................................ 363

Preparing the Example Project ............................................................................... 363 Generating Outgoing URLs in Views ....................................................................... 364

Using the Routing System to Generate an Outgoing URL .............................................. 364 Targeting Other Controllers ........................................................................................... 368 Passing Extra Values...................................................................................................... 369 Specifying HTML Attributes ........................................................................................... 371 Generating Fully Qualified URLs in Links ....................................................................... 371 Generating URLs (and Not Links) ................................................................................... 372 Generating Outgoing URLs in Action Methods ............................................................... 373 Generating a URL from a Specific Route ........................................................................ 374

Customizing the Routing System ........................................................................... 375 Creating a Custom RouteBase Implementation ............................................................. 375 Creating a Custom Route Handler .................................................................................. 379

Working with Areas ................................................................................................ 381 Creating an Area ............................................................................................................ 381 Populating an Area ......................................................................................................... 383 Resolving the Ambiguous Controller Issue .................................................................... 385 Generating Links to Actions in Areas ............................................................................. 387

URL Schema Best Practices ................................................................................... 388 Make Your URLs Clean and Human-Friendly ................................................................. 388 GET and POST: Pick the Right One ................................................................................. 389

Summary ................................................................................................................ 389 ■ Chapter 15: Controllers and Actions ...................................................................... 391

Introducing the Controller ...................................................................................... 391 Preparing the Example Project ...................................................................................... 391 Creating a Controller with IController ............................................................................ 391 Creating a Controller by Deriving from the Controller Class .......................................... 393

Receiving Input ....................................................................................................... 394 Getting Data from Context Objects ................................................................................ 395 Using Action Method Parameters .................................................................................. 396

Page 14: Pro ASP.NET MVC 4 - link.springer.com3A978-1-4302-4237-6%2F… · Part 1: Introducing ASP.NET MVC 4 .....1 Chapter 1: What’s the Big Idea? ..... 3 Chapter 2: Your First MVC Application

CONTENTS ■

xv

Producing Output.................................................................................................... 398 Understanding Action Results ........................................................................................ 399 Returning HTML by Rendering a View ........................................................................... 403 Passing Data from an Action Method to a View ............................................................. 407 Performing Redirections ................................................................................................ 411 Returning Errors and HTTP Codes .................................................................................. 415

Summary ................................................................................................................ 417 ■ Chapter 16: Filters .................................................................................................. 419

Using Filters ........................................................................................................... 419 Introducing the Four Basic Types of Filters ................................................................... 421 Applying Filters to Controllers and Action Methods ....................................................... 421

Creating the Example Project ................................................................................. 422 Using Authorization Filters ..................................................................................... 423

Applying the Custom Authorization Filter ...................................................................... 425 Using the Built-in Authorization Filter ............................................................................ 426

Using Exception Filters ........................................................................................... 427 Creating an Exception Filter ........................................................................................... 427 Applying the Exception Filter ......................................................................................... 429 Using a View to Respond to an Exception ...................................................................... 431 Using the Built-In Exception Filter ................................................................................. 434

Using Action Filters ................................................................................................ 437 Implementing the OnActionExecuting Method ............................................................... 437 Implementing the OnActionExecuted Method ................................................................ 439

Using Result Filters ................................................................................................ 441 Using the Built-In Action and Result Filter Class ........................................................... 442

Using Other Filter Features ..................................................................................... 444 Filtering Without Attributes ............................................................................................ 444 Using Global Filters ........................................................................................................ 446 Ordering Filter Execution ............................................................................................... 447

Using the Built-in Filters......................................................................................... 449 Using the RequireHttps Filter ......................................................................................... 450 Using the OutputCache Filter ......................................................................................... 450

Summary ................................................................................................................ 454 ■ Chapter 17: Controller Extensibility ....................................................................... 455

Page 15: Pro ASP.NET MVC 4 - link.springer.com3A978-1-4302-4237-6%2F… · Part 1: Introducing ASP.NET MVC 4 .....1 Chapter 1: What’s the Big Idea? ..... 3 Chapter 2: Your First MVC Application

■ CONTENTS

xvi

Creating the Example Project ................................................................................. 455 Creating a Custom Controller Factory .................................................................... 457

Dealing with the Fallback Controller .............................................................................. 459 Instantiating Controller Classes ..................................................................................... 460 Implementing the Other Interface Methods ................................................................... 460 Registering a Custom Controller Factory ....................................................................... 460

Working with the Built-In Controller Factory ......................................................... 461 Prioritizing Namespaces ................................................................................................ 462 Customizing DefaultControllerFactory Controller Instantiation ...................................... 463

Creating a Custom Action Invoker .......................................................................... 466 Using the Built-In Action Invoker ........................................................................... 468

Using a Custom Action Name ........................................................................................ 468 Using Action Method Selection ...................................................................................... 470

Improving Performance with Specialized Controllers ............................................ 476 Using Sessionless Controllers ........................................................................................ 476 Using Asynchronous Controllers .................................................................................... 478

Summary ................................................................................................................ 483 ■ Chapter 18: Views .................................................................................................. 485

Creating a Custom View Engine ............................................................................. 485 Creating the Example Project ........................................................................................ 487 Creating a Custom IView ................................................................................................ 488 Creating an IViewEngine Implementation ...................................................................... 489 Registering a Custom View Engine ................................................................................ 490 Testing the View Engine ................................................................................................ 490

Working with the Razor Engine .............................................................................. 492 Creating the Example Project ........................................................................................ 493 Understanding Razor View Rendering ........................................................................... 493 Configuring the View Search Locations ......................................................................... 495

Adding Dynamic Content to a Razor View .............................................................. 498 Using Sections ............................................................................................................... 498 Using Partial Views ........................................................................................................ 504 Using Child Actions ........................................................................................................ 508

Summary ................................................................................................................ 510 ■ Chapter 19: Helper Methods ................................................................................... 511

Page 16: Pro ASP.NET MVC 4 - link.springer.com3A978-1-4302-4237-6%2F… · Part 1: Introducing ASP.NET MVC 4 .....1 Chapter 1: What’s the Big Idea? ..... 3 Chapter 2: Your First MVC Application

CONTENTS ■

xvii

Creating the Example Project ................................................................................. 511 Creating Custom Helper Methods ........................................................................... 513

Creating an Inline Helper Method .................................................................................. 513 Creating an External Helper Method .............................................................................. 515 Managing String Encoding in a Helper Method ............................................................. 518

Using the Built-In Form Helper Methods ................................................................ 523 Creating Form Elements ................................................................................................ 523 Specifying the Route Used by a Form ............................................................................ 530 Using Input Helpers ........................................................................................................ 532 Creating Select Elements ............................................................................................... 537

Summary ................................................................................................................ 539 ■ Chapter 20: Templated Helper Methods ................................................................. 541

Reviewing the Example Project .............................................................................. 541 Using Templated Helper Methods ........................................................................... 543

Generating Label and Display Elements ........................................................................ 547 Using Whole-Model Template Helpers ........................................................................... 550

Using Model Metadata ............................................................................................ 552 Using Metadata to Control Editing and Visibility ............................................................ 553 Using Metadata for Labels ............................................................................................. 555 Using Metadata for Data Values .................................................................................... 557 Using Metadata to Select a Display Template ............................................................... 559 Applying Metadata to a Buddy Class ............................................................................. 561 Working with Complex Type Properties ......................................................................... 562

Customizing the Templated View Helper System ................................................... 564 Creating a Custom Editor Template ............................................................................... 564 Creating a Generic Template ......................................................................................... 565 Replacing the Built-in Templates ................................................................................... 566

Summary ................................................................................................................ 567 ■ Chapter 21: URL and Ajax Helper Methods ............................................................. 569

Reviewing and Preparing the Example Project ...................................................... 569 Creating Basic Links and URLs ............................................................................... 571 Using MVC Unobtrusive Ajax .................................................................................. 573

Creating the Synchronous Form View ............................................................................ 574 Preparing the Project for Unobtrusive Ajax .................................................................... 575

Page 17: Pro ASP.NET MVC 4 - link.springer.com3A978-1-4302-4237-6%2F… · Part 1: Introducing ASP.NET MVC 4 .....1 Chapter 1: What’s the Big Idea? ..... 3 Chapter 2: Your First MVC Application

■ CONTENTS

xviii

Creating an Unobtrusive Ajax Form ........................................................................ 577 Preparing the Controller ................................................................................................. 577 Creating the Ajax Form .................................................................................................. 578 Understanding How Unobtrusive Ajax Works ................................................................ 580

Setting Ajax Options ............................................................................................... 581 Ensuring Graceful Degradation ...................................................................................... 581 Providing the User with Feedback While Making an Ajax Request ................................ 583 Prompting the User Before Making a Request ............................................................... 584

Creating Ajax Links ................................................................................................ 585 Ensuring Graceful Degradation for Links ....................................................................... 587

Working with Ajax Callbacks .................................................................................. 587 Working with JSON ................................................................................................. 590

Adding JSON Support to the Controller .......................................................................... 590 Processing JSON in the Browser ................................................................................... 591 Preparing Data for Encoding .......................................................................................... 593 Detecting Ajax Requests in the Action Method .............................................................. 595

Summary ................................................................................................................ 598 ■ Chapter 22: Model Binding ..................................................................................... 599

Preparing the Example Project ............................................................................... 599 Understanding Model Binding ................................................................................ 601 Using the Default Model Binder .............................................................................. 603

Binding to Simple Types ................................................................................................ 603 Binding to Complex Types ............................................................................................. 607 Binding to Arrays and Collections .................................................................................. 614

Manually Invoking Model Binding .......................................................................... 619 Dealing with Binding Errors ........................................................................................... 621

Customizing the Model Binding System ................................................................. 621 Creating a Custom Value Provider ................................................................................. 622 Creating a Custom Model Binder ................................................................................... 625 Registering the Custom Model Binder ........................................................................... 627

Summary ................................................................................................................ 628 ■ Chapter 23: Model Validation ................................................................................. 629

Creating the Example Project ................................................................................. 629 Explicitly Validating a Model .................................................................................. 631

Page 18: Pro ASP.NET MVC 4 - link.springer.com3A978-1-4302-4237-6%2F… · Part 1: Introducing ASP.NET MVC 4 .....1 Chapter 1: What’s the Big Idea? ..... 3 Chapter 2: Your First MVC Application

CONTENTS ■

xix

Displaying Validation Errors to the User ........................................................................ 633 Displaying Validation Messages ............................................................................. 634

Displaying Property-Level Validation Messages ............................................................ 638 Using Alternative Validation Techniques ................................................................ 639

Performing Validation in the Model Binder .................................................................... 639 Specifying Validation Rules Using Metadata ................................................................. 641 Defining Self-Validating Models .................................................................................... 647

Performing Client-Side Validation .......................................................................... 649 Enabling and Disabling Client-Side Validation ............................................................... 649 Using Client-Side Validation .......................................................................................... 650 Understanding How Client-Side Validation Works ......................................................... 652

Performing Remote Validation ............................................................................... 653 Summary ................................................................................................................ 656

■ Chapter 24: Bundles and Display Modes ................................................................ 657

Understanding the Default Script Libraries ............................................................ 657 Preparing the Example Application ........................................................................ 659 Managing Scripts and Style Sheets ........................................................................ 662

Profiling Script and Style Sheet Loading ....................................................................... 662 Using Script and Style Bundles .............................................................................. 664

Applying Bundles ........................................................................................................... 667 Using the Scripts Section ............................................................................................... 669 Profiling the Changes ..................................................................................................... 670

Targeting Mobile Devices ....................................................................................... 673 Taking Stock of the Application ..................................................................................... 673 Using Mobile Specific Layouts and Views ..................................................................... 674 Creating Custom Display Modes .................................................................................... 676

Summary ................................................................................................................ 678 ■ Chapter 25: Web API ............................................................................................... 679

Understanding the Web API .................................................................................... 679 Creating the Web API Application ........................................................................... 680

Creating the Model and Repository ................................................................................ 680 Creating the Home Controller ........................................................................................ 682 Creating the View and the CSS ...................................................................................... 683

Creating the API Controller ..................................................................................... 685

Page 19: Pro ASP.NET MVC 4 - link.springer.com3A978-1-4302-4237-6%2F… · Part 1: Introducing ASP.NET MVC 4 .....1 Chapter 1: What’s the Big Idea? ..... 3 Chapter 2: Your First MVC Application

■ CONTENTS

xx

Testing the API Controller .............................................................................................. 687 Understanding How the API Controller Works ........................................................ 689

Understanding API Controller Action Selection .............................................................. 689 Mapping HTTP Methods to Action Methods ................................................................... 690

Writing the JavaScript Code to Use the Web API .................................................... 691 Creating the Basic Functionality .................................................................................... 692 Adding Support for Editing New Reservations ............................................................... 694 Adding Support for Deleting Reservations ..................................................................... 696 Adding Support for Creating Reservations ..................................................................... 697

Summary ................................................................................................................ 698 ■ Chapter 26: Deployment ......................................................................................... 699

Preparing an Application for Deployment .............................................................. 700 Detecting View Errors .................................................................................................... 700 Disabling Debug Mode ................................................................................................... 702 Removing Unused Connection Strings ........................................................................... 703

Preparing Windows Azure ...................................................................................... 704 Creating the Web Site and Database ............................................................................. 705 Preparing the Database for Remote Administration ...................................................... 707 Creating the Schema ..................................................................................................... 708

Deploying the Application ...................................................................................... 710 Summary ................................................................................................................ 716

■ Index ....................................................................................................................... 717

Page 20: Pro ASP.NET MVC 4 - link.springer.com3A978-1-4302-4237-6%2F… · Part 1: Introducing ASP.NET MVC 4 .....1 Chapter 1: What’s the Big Idea? ..... 3 Chapter 2: Your First MVC Application

xxi

About the Author

Adam Freeman is an experienced IT professional who has held senior positions in a range of companies, most recently serving as chief technology officer and chief operating officer of a global bank. Now retired, he spends his time writing and running.

Page 21: Pro ASP.NET MVC 4 - link.springer.com3A978-1-4302-4237-6%2F… · Part 1: Introducing ASP.NET MVC 4 .....1 Chapter 1: What’s the Big Idea? ..... 3 Chapter 2: Your First MVC Application

xxii

About the Technical Reviewer

Fabio Claudio Ferracchiati is a senior consultant and a senior analyst/developer using Microsoft technologies. He works for Brain Force (http://www.brainforce.com) in its Italian branch (http://www.brainforce.it). He is a Microsoft Certified Solution Developer for .NET, a Microsoft Certified Application Developer for .NET, a Microsoft Certified Professional, and a prolific author and technical reviewer. Over the past 10 years, he’s written articles for Italian and international magazines and coauthored more than 10 books on a variety of computer topics.

Page 22: Pro ASP.NET MVC 4 - link.springer.com3A978-1-4302-4237-6%2F… · Part 1: Introducing ASP.NET MVC 4 .....1 Chapter 1: What’s the Big Idea? ..... 3 Chapter 2: Your First MVC Application

xxiii

Acknowledgments

I would like to thank everyone at Apress for working so hard to bring this book to print. In particular, I would like to thank Ewan Buckingham for commissioning and editing this title and Christine Ricketts for keeping track of everything. I would also like to thank the technical reviewer, Fabio, whose efforts made this book far better than it otherwise would have been.

—Adam Freeman