Upload
nguyencong
View
214
Download
1
Embed Size (px)
Citation preview
Pro ASP.NET MVC 5
Adam Freeman
Pro ASP.NET MVC 5
Copyright © 2013 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-13 (pbk): 978-1-4302-6529-0
ISBN-13 (electronic): 978-1-4302-6530-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 ManningLead Editor: Ewan BuckinghamTechnical Reviewer: Fabio Claudio FerracchiatiEditorial Board: Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell, Louise Corrigan, Jim DeWolf,
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, Steve Weiss
Coordinating Editor: Kevin SheaCopy Editor: Larissa ShmailoCompositor: SPi GlobalIndexer: SPi GlobalArtist: SPi GlobalCover 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 material referenced by the author in this text is available to readers at www.apress.com/9781430257882. For detailed information about how to locate your book’s source code, go to www.apress.com/source-code/.
Dedicated to my lovely wife, Jacqui Griffyth.
v
Contents at a Glance
About the Author �������������������������������������������������������������������������������������������������������������� xxv
About the Technical Reviewer ���������������������������������������������������������������������������������������� xxvii
Chapter 1: Putting ASP�NET MVC in Context ■ ����������������������������������������������������������������������1
Chapter 2: Your First MVC Application ■ ����������������������������������������������������������������������������11
Chapter 3: The MVC Pattern ■ ���������������������������������������������������������������������������������������������51
Chapter 4: Essential Language Features ■ �������������������������������������������������������������������������67
Chapter 5: Working with Razor ■ ���������������������������������������������������������������������������������������95
Chapter 6: Essential Tools for MVC ■ ��������������������������������������������������������������������������������119
Chapter 7: SportsStore: A Real Application ■ �������������������������������������������������������������������155
Chapter 8: SportsStore: Navigation ■ �������������������������������������������������������������������������������197
Chapter 9: SportsStore: Completing the Cart ■ ����������������������������������������������������������������227
Chapter 10: SportsStore: Mobile ■ �����������������������������������������������������������������������������������255
Chapter 11: SportsStore: Administration ■ ����������������������������������������������������������������������275
Chapter 12: SportsStore: Security & Finishing Touches ■ ������������������������������������������������305
Chapter 13: Deployment ■ ������������������������������������������������������������������������������������������������329
Chapter 14: Overview of MVC Projects ■ ��������������������������������������������������������������������������345
Chapter 15: URL Routing ■ ������������������������������������������������������������������������������������������������369
Chapter 16: Advanced Routing Features ■ �����������������������������������������������������������������������415
Chapter 17: Controllers and Actions ■ ������������������������������������������������������������������������������451
Chapter 18: Filters ■ ���������������������������������������������������������������������������������������������������������483
■ Contents at a GlanCe
vi
Chapter 19: Controller Extensibility ■ �������������������������������������������������������������������������������529
Chapter 20: Views ■ ���������������������������������������������������������������������������������������������������������559
Chapter 21: Helper Methods ■ ������������������������������������������������������������������������������������������587
Chapter 22: Templated Helper Methods ■ ������������������������������������������������������������������������617
Chapter 23: URL and Ajax Helper Methods ■ ��������������������������������������������������������������������645
Chapter 24: Model Binding ■ ��������������������������������������������������������������������������������������������677
Chapter 25: Model Validation ■ ����������������������������������������������������������������������������������������709
Chapter 26: Bundles ■ ������������������������������������������������������������������������������������������������������741
Chapter 27: Web API and Single-page Applications ■ ������������������������������������������������������755
Index ���������������������������������������������������������������������������������������������������������������������������������785
vii
Contents
About the Author �������������������������������������������������������������������������������������������������������������� xxv
About the Technical Reviewer ���������������������������������������������������������������������������������������� xxvii
Chapter 1: Putting ASP�NET MVC in Context ■ ����������������������������������������������������������������������1
Understanding the History of ASP.NET ...........................................................................................1
What Is Wrong with ASP.NET Web Forms? ............................................................................................................. 2
Web Development Today ...............................................................................................................3
Web Standards and REST ...................................................................................................................................... 3
Agile and Test-Driven Development ....................................................................................................................... 3
Ruby on Rails ......................................................................................................................................................... 4
Node.js ................................................................................................................................................................... 4
Key Benefits of ASP.NET MVC ........................................................................................................5
MVC Architecture ................................................................................................................................................... 5
Extensibility ........................................................................................................................................................... 5
Tight Control over HTML and HTTP ........................................................................................................................ 6
Testability .............................................................................................................................................................. 6
Powerful Routing System ...................................................................................................................................... 7
Built on the Best Parts of the ASP.NET Platform .................................................................................................... 7
Modern API ............................................................................................................................................................ 7
ASP.NET MVC Is Open Source ................................................................................................................................ 8
What Do I Need to Know? ..............................................................................................................8
What Is the Structure of This Book? ..............................................................................................8
Part 1: Introducing ASP.NET MVC 5 ........................................................................................................................ 8
Part 2: ASP.NET MVC in Detail ................................................................................................................................ 8
■ Contents
viii
What’s New in this Edition? ...........................................................................................................9
Where Can I Get the Example Code? .............................................................................................9
What Software Do I Need for This Book? ....................................................................................10
Credits .........................................................................................................................................10
Summary .....................................................................................................................................10
Chapter 2: Your First MVC Application ■ ����������������������������������������������������������������������������11
Preparing Visual Studio ...............................................................................................................11
Creating a New ASP.NET MVC Project .........................................................................................11
Adding the First Controller ................................................................................................................................... 15
Understanding Routes ......................................................................................................................................... 19
Rendering Web Pages .................................................................................................................19
Creating and Rendering a View ........................................................................................................................... 19
Adding Dynamic Output ....................................................................................................................................... 23
Creating a Simple Data-Entry Application ...................................................................................25
Setting the Scene ................................................................................................................................................ 25
Designing a Data Model ....................................................................................................................................... 26
Linking Action Methods ....................................................................................................................................... 27
Building the Form ................................................................................................................................................ 30
Setting the Start URL ........................................................................................................................................... 32
Handling Forms ................................................................................................................................................... 33
Adding Validation ................................................................................................................................................. 36
Styling the Content .............................................................................................................................................. 42
Completing the Example ...................................................................................................................................... 48
Summary .....................................................................................................................................49
Chapter 3: The MVC Pattern ■ ���������������������������������������������������������������������������������������������51
The History of MVC ......................................................................................................................51
Understanding the MVC Pattern ..................................................................................................51
Understanding the Domain Model ....................................................................................................................... 52
The ASP.NET Implementation of MVC .................................................................................................................. 52
Comparing MVC to Other Patterns ....................................................................................................................... 53
■ Contents
ix
Building Loosely Coupled Components .......................................................................................56
Using Dependency Injection ................................................................................................................................ 57
Using a Dependency Injection Container ............................................................................................................. 59
Getting Started with Automated Testing ......................................................................................60
Understanding Unit Testing .................................................................................................................................. 60
Understanding Integration Testing ....................................................................................................................... 65
Summary .....................................................................................................................................66
Chapter 4: Essential Language Features ■ �������������������������������������������������������������������������67
Preparing the Example Project ....................................................................................................67
Adding the System.Net.Http Assembly ................................................................................................................ 69
Using Automatically Implemented Properties .............................................................................69
Using Object and Collection Initializers .......................................................................................72
Using Extension Methods ............................................................................................................74
Applying Extension Methods to an Interface ....................................................................................................... 76
Creating Filtering Extension Methods .................................................................................................................. 79
Using Lambda Expressions .........................................................................................................80
Using Automatic Type Inference ..................................................................................................84
Using Anonymous Types ..............................................................................................................84
Performing Language Integrated Queries ...................................................................................86
Understanding Deferred LINQ Queries ................................................................................................................. 90
Using Async Methods ..................................................................................................................91
Applying the async and await Keywords ............................................................................................................. 93
Summary .....................................................................................................................................94
Chapter 5: Working with Razor ■ ���������������������������������������������������������������������������������������95
Preparing the Example Project ....................................................................................................95
Defining the Model .............................................................................................................................................. 95
Defining the Controller ......................................................................................................................................... 96
Creating the View ................................................................................................................................................ 97
■ Contents
x
Working with the Model Object ...................................................................................................97
Working with Layouts ..................................................................................................................99
Creating the Layout ........................................................................................................................................... 100
Applying a Layout .............................................................................................................................................. 102
Using a View Start File ....................................................................................................................................... 102
Demonstrating Shared Layouts ......................................................................................................................... 103
Using Razor Expressions ...........................................................................................................107
Inserting Data Values ......................................................................................................................................... 108
Setting Attribute Values ..................................................................................................................................... 110
Using Conditional Statements ........................................................................................................................... 112
Enumerating Arrays and Collections .................................................................................................................. 115
Dealing with Namespaces ................................................................................................................................. 117
Summary ...................................................................................................................................118
Chapter 6: Essential Tools for MVC ■ ��������������������������������������������������������������������������������119
Preparing the Example Project ..................................................................................................120
Creating the Model Classes ............................................................................................................................... 120
Adding the Controller ......................................................................................................................................... 121
Adding the View ................................................................................................................................................. 122
Using Ninject .............................................................................................................................123
Understanding the Problem ............................................................................................................................... 123
Adding Ninject to the Visual Studio Project ....................................................................................................... 125
Getting Started with Ninject .............................................................................................................................. 125
Setting up MVC Dependency Injection ............................................................................................................... 127
Creating Chains of Dependency ......................................................................................................................... 130
Specifying Property and Constructor Parameter Values .................................................................................... 131
Using Conditional Binding .................................................................................................................................. 133
Setting the Object Scope ................................................................................................................................... 134
Unit Testing with Visual Studio ..................................................................................................137
Creating the Unit Test Project ............................................................................................................................ 137
Creating the Unit Tests ....................................................................................................................................... 139
■ Contents
xi
Running the Unit Tests (and Failing) .................................................................................................................. 142
Implementing the Feature ................................................................................................................................. 143
Testing and Fixing the Code............................................................................................................................... 144
Using Moq .................................................................................................................................145
Understanding the Problem ............................................................................................................................... 146
Adding Moq to the Visual Studio Project............................................................................................................ 147
Adding a Mock Object to a Unit Test .................................................................................................................. 147
Creating a More Complex Mock Object ............................................................................................................. 150
Summary ...................................................................................................................................153
Chapter 7: SportsStore: A Real Application ■ �������������������������������������������������������������������155
Getting Started ..........................................................................................................................156
Creating the Visual Studio Solution and Projects............................................................................................... 156
Installing the Tool Packages .............................................................................................................................. 158
Adding References Between Projects ............................................................................................................... 158
Setting Up the DI Container ............................................................................................................................... 159
Running the Application ..................................................................................................................................... 160
Starting the Domain Model........................................................................................................160
Creating an Abstract Repository ........................................................................................................................ 161
Making a Mock Repository ................................................................................................................................ 162
Displaying a List of Products .....................................................................................................163
Adding a Controller ............................................................................................................................................ 163
Adding the Layout, View Start File and View ..................................................................................................... 165
Setting the Default Route .................................................................................................................................. 166
Running the Application ..................................................................................................................................... 167
Preparing a Database ................................................................................................................168
Creating the Database ....................................................................................................................................... 169
Defining the Database Schema ......................................................................................................................... 171
Adding Data to the Database ............................................................................................................................. 173
Creating the Entity Framework Context ............................................................................................................. 174
Creating the Product Repository ........................................................................................................................ 176
■ Contents
xii
Adding Pagination .....................................................................................................................178
Displaying Page Links........................................................................................................................................ 180
Improving the URLs ........................................................................................................................................... 189
Styling the Content ....................................................................................................................190
Installing the Bootstrap Package ....................................................................................................................... 190
Applying Bootstrap Styles to the Layout ............................................................................................................ 191
Creating a Partial View ...................................................................................................................................... 193
Summary ...................................................................................................................................196
Chapter 8: SportsStore: Navigation ■ �������������������������������������������������������������������������������197
Adding Navigation Controls .......................................................................................................197
Filtering the Product List ................................................................................................................................... 197
Refining the URL Scheme .................................................................................................................................. 202
Building a Category Navigation Menu ............................................................................................................... 204
Correcting the Page Count ................................................................................................................................. 212
Building the Shopping Cart........................................................................................................214
Defining the Cart Entity ...................................................................................................................................... 215
Adding the Add to Cart Buttons ......................................................................................................................... 219
Implementing the Cart Controller ...................................................................................................................... 220
Displaying the Contents of the Cart ................................................................................................................... 222
Summary ...................................................................................................................................225
Chapter 9: SportsStore: Completing the Cart ■ ����������������������������������������������������������������227
Using Model Binding .................................................................................................................227
Creating a Custom Model Binder ....................................................................................................................... 227
Completing the Cart ..................................................................................................................232
Removing Items from the Cart ........................................................................................................................... 232
Adding the Cart Summary ................................................................................................................................. 234
Submitting Orders .....................................................................................................................236
Extending the Domain Model ............................................................................................................................. 236
Adding the Checkout Process ............................................................................................................................ 237
Implementing the Order Processor .................................................................................................................... 244
■ Contents
xiii
Registering the Implementation ........................................................................................................................ 247
Completing the Cart Controller .......................................................................................................................... 248
Displaying Validation Errors ............................................................................................................................... 252
Displaying a Summary Page .............................................................................................................................. 254
Summary ...................................................................................................................................254
Chapter 10: SportsStore: Mobile ■ �����������������������������������������������������������������������������������255
Putting Mobile Web Development in Context ............................................................................255
Doing Nothing (Or As Little As Possible) ............................................................................................................ 255
Using Responsive Design ..........................................................................................................257
Creating a Responsive Header........................................................................................................................... 258
Creating a Responsive Product List ................................................................................................................... 261
Creating Mobile Specific Content ..............................................................................................269
Creating a Mobile Layout ................................................................................................................................... 270
Creating the Mobile Views ................................................................................................................................. 271
Summary ...................................................................................................................................274
Chapter 11: SportsStore: Administration ■ ����������������������������������������������������������������������275
Adding Catalog Management ....................................................................................................275
Creating a CRUD Controller ................................................................................................................................ 275
Creating a New Layout ...................................................................................................................................... 277
Implementing the List View ............................................................................................................................... 278
Editing Products ................................................................................................................................................ 282
Creating New Products ...................................................................................................................................... 297
Deleting Products .............................................................................................................................................. 300
Summary ...................................................................................................................................303
Chapter 12: SportsStore: Security & Finishing Touches ■ ������������������������������������������������305
Securing the Administration Controller .....................................................................................305
Creating a Basic Security Policy ........................................................................................................................ 305
Applying Authorization with Filters .................................................................................................................... 307
Creating the Authentication Provider ................................................................................................................. 309
■ Contents
xiv
Creating the Account Controller ......................................................................................................................... 311
Creating the View .............................................................................................................................................. 312
Image Uploads ...........................................................................................................................315
Extending the Database ..................................................................................................................................... 316
Enhancing the Domain Model ............................................................................................................................ 316
Creating the Upload User Interface Elements .................................................................................................... 317
Saving Images to the Database ......................................................................................................................... 319
Implementing the GetImage Action Method ...................................................................................................... 321
Displaying Product Images ................................................................................................................................ 325
Summary ...................................................................................................................................327
Chapter 13: Deployment ■ ������������������������������������������������������������������������������������������������329
Preparing Windows Azure .........................................................................................................330
Creating the Web Site and Database ................................................................................................................. 330
Preparing the Database for Remote Administration .......................................................................................... 333
Creating the Schema ......................................................................................................................................... 334
Deploying the Application ..........................................................................................................336
Summary ...................................................................................................................................343
Chapter 14: Overview of MVC Projects ■ ��������������������������������������������������������������������������345
Working with Visual Studio MVC Projects .................................................................................345
Creating the Project ........................................................................................................................................... 345
Understanding MVC Conventions ...................................................................................................................... 349
Debugging MVC Applications ....................................................................................................351
Preparing the Example Project .......................................................................................................................... 351
Launching the Visual Studio Debugger .............................................................................................................. 355
Causing the Visual Studio Debugger to Break ................................................................................................... 357
Using Edit and Continue .................................................................................................................................... 363
Using Browser Link ...................................................................................................................366
Summary ...................................................................................................................................368
■ Contents
xv
Chapter 15: URL Routing ■ ������������������������������������������������������������������������������������������������369
Preparing the Example Project ..................................................................................................370
Creating the Example Controllers ..................................................................................................................... 371
Creating the View .............................................................................................................................................. 372
Setting the Start URL and Testing the Application ............................................................................................. 373
Introducing URL Patterns ..........................................................................................................373
Creating and Registering a Simple Route .................................................................................375
Using the Simple Route ..................................................................................................................................... 377
Defining Default Values .............................................................................................................381
Using Static URL Segments .......................................................................................................383
Defining Custom Segment Variables .........................................................................................388
Using Custom Variables as Action Method Parameters ..................................................................................... 391
Defining Optional URL Segments ....................................................................................................................... 391
Defining Variable-Length Routes ....................................................................................................................... 394
Prioritizing Controllers by Namespaces ............................................................................................................. 396
Constraining Routes ..................................................................................................................399
Constraining a Route Using a Regular Expression ............................................................................................. 399
Constraining a Route to a Set of Specific Values ............................................................................................... 400
Constraining a Route Using HTTP Methods ....................................................................................................... 401
Using Type and Value Constraints ...................................................................................................................... 402
Defining a Custom Constraint ............................................................................................................................ 405
Using Attribute Routing .............................................................................................................407
Enabling and Applying Attribute Routing .......................................................................................................... 408
Creating Routes with Segment Variables .......................................................................................................... 410
Applying Route Constraints ............................................................................................................................... 411
Using a Route Prefix .......................................................................................................................................... 413
Summary ...................................................................................................................................414
■ Contents
xvi
Chapter 16: Advanced Routing Features ■ �����������������������������������������������������������������������415
Preparing the Example Project ..................................................................................................416
Simplifying the Routes....................................................................................................................................... 416
Adding the Optimization Package ...................................................................................................................... 416
Updating the Unit Test Project ........................................................................................................................... 416
Generating Outgoing URLs in Views .........................................................................................417
Using the Routing System to Generate an Outgoing URL .................................................................................. 417
Targeting Other Controllers ................................................................................................................................ 420
Passing Extra Values .......................................................................................................................................... 422
Specifying HTML Attributes ............................................................................................................................... 424
Generating Fully Qualified URLs in Links ........................................................................................................... 425
Generating URLs (and Not Links) ....................................................................................................................... 426
Generating Outgoing URLs in Action Methods ................................................................................................... 427
Generating a URL from a Specific Route ........................................................................................................... 428
Customizing the Routing System ..............................................................................................430
Creating a Custom RouteBase Implementation ................................................................................................. 430
Creating a Custom Route Handler ..................................................................................................................... 434
Working with Areas ...................................................................................................................436
Creating an Area ................................................................................................................................................ 436
Populating an Area ............................................................................................................................................ 438
Resolving the Ambiguous Controller Issue ........................................................................................................ 440
Creating Areas with Attributes ........................................................................................................................... 442
Generating Links to Actions in Areas ................................................................................................................. 443
Routing Requests for Disk Files ................................................................................................443
Configuring the Application Server .................................................................................................................... 445
Defining Routes for Disk Files ........................................................................................................................... 446
Bypassing the Routing System ..................................................................................................448
URL Schema Best Practices ......................................................................................................449
Make Your URLs Clean and Human-Friendly ..................................................................................................... 449
GET and POST: Pick the Right One ..................................................................................................................... 450
Summary ...................................................................................................................................450
■ Contents
xvii
Chapter 17: Controllers and Actions ■ ������������������������������������������������������������������������������451
Preparing the Example Project ..................................................................................................452
Setting the Start URL ......................................................................................................................................... 452
Introducing the Controller .........................................................................................................452
Creating a Controller with IController ................................................................................................................ 452
Creating a Controller by Deriving from the Controller Class .............................................................................. 455
Receiving Request Data ............................................................................................................456
Getting Data from Context Objects .................................................................................................................... 457
Using Action Method Parameters ...................................................................................................................... 458
Producing Output ......................................................................................................................460
Understanding Action Results ............................................................................................................................ 462
Returning HTML by Rendering a View ............................................................................................................... 465
Passing Data from an Action Method to a View ................................................................................................. 469
Performing Redirections .................................................................................................................................... 474
Returning Errors and HTTP Codes ..................................................................................................................... 479
Summary ...................................................................................................................................481
Chapter 18: Filters ■ ���������������������������������������������������������������������������������������������������������483
Preparing the Example Project ..................................................................................................483
Setting the Start URL and Testing the Application ............................................................................................. 486
Using Filters ..............................................................................................................................486
Introducing the Filter Types ............................................................................................................................... 487
Applying Filters to Controllers and Action Methods ........................................................................................... 488
Using Authorization Filters ........................................................................................................489
Applying the Custom Authorization Filter .......................................................................................................... 491
Using the Built-in Authorization Filter ................................................................................................................ 492
Using Authentication Filters ......................................................................................................493
Understanding the IAuthenticationFilter Interface ............................................................................................. 493
Implementing the Authentication Check ........................................................................................................... 495
Combining Authentication and Authorization Filters .......................................................................................... 497
Handling the Final Challenge Request ............................................................................................................... 498
■ Contents
xviii
Using Exception Filters ..............................................................................................................499
Creating an Exception Filter .............................................................................................................................. 499
Applying the Exception Filter ............................................................................................................................. 501
Using a View to Respond to an Exception.......................................................................................................... 503
Using the Built-in Exception Filter ..................................................................................................................... 506
Using Action Filters ...................................................................................................................509
Implementing the OnActionExecuting Method .................................................................................................. 509
Implementing the OnActionExecuted Method ................................................................................................... 512
Using Result Filters ...................................................................................................................513
Using the Built-in Action and Result Filter Class ............................................................................................... 515
Using Other Filter Features .......................................................................................................517
Filtering Without Attributes ................................................................................................................................ 517
Using Global Filters ............................................................................................................................................ 519
Ordering Filter Execution ................................................................................................................................... 521
Overriding Filters ............................................................................................................................................... 524
Summary ...................................................................................................................................527
Chapter 19: Controller Extensibility ■ �������������������������������������������������������������������������������529
Preparing the Example Project ..................................................................................................530
Setting the Start URL ......................................................................................................................................... 532
Creating a Custom Controller Factory .......................................................................................532
Dealing with the Fallback Controller ................................................................................................................. 534
Instantiating Controller Classes ......................................................................................................................... 535
Implementing the Other Interface Methods ....................................................................................................... 535
Registering a Custom Controller Factory ........................................................................................................... 536
Working with the Built-in Controller Factory .............................................................................536
Prioritizing Namespaces .................................................................................................................................... 537
Customizing DefaultControllerFactory Controller Instantiation ......................................................................... 538
Creating a Custom Action Invoker .............................................................................................541
■ Contents
xix
Using the Built-in Action Invoker ...............................................................................................542
Using a Custom Action Name ............................................................................................................................ 543
Using Action Method Selection .......................................................................................................................... 545
Improving Performance with Specialized Controllers ...............................................................551
Using Sessionless Controllers ........................................................................................................................... 551
Using Asynchronous Controllers ........................................................................................................................ 553
Summary ...................................................................................................................................558
Chapter 20: Views ■ ���������������������������������������������������������������������������������������������������������559
Creating a Custom View Engine ................................................................................................559
Preparing the Example Project .......................................................................................................................... 562
Creating a Custom IView ................................................................................................................................... 563
Creating an IViewEngine Implementation .......................................................................................................... 564
Registering a Custom View Engine .................................................................................................................... 565
Testing the View Engine ..................................................................................................................................... 566
Working with the Razor Engine .................................................................................................568
Preparing the Example Project .......................................................................................................................... 568
Understanding Razor View Rendering ............................................................................................................... 569
Configuring the View Search Locations ............................................................................................................. 570
Adding Dynamic Content to a Razor View .................................................................................573
Using Layout Sections ....................................................................................................................................... 574
Using Partial Views ............................................................................................................................................ 579
Using Child Actions ............................................................................................................................................ 583
Summary ...................................................................................................................................585
Chapter 21: Helper Methods ■ ������������������������������������������������������������������������������������������587
Preparing the Example Project ..................................................................................................587
Setting the Start URL ......................................................................................................................................... 588
Testing the Example Application ........................................................................................................................ 589
Creating Custom Helper Methods .............................................................................................589
Creating an Inline Helper Method ...................................................................................................................... 589
Creating an External Helper Method .................................................................................................................. 591
Managing String Encoding in a Helper Method ................................................................................................. 595
■ Contents
xx
Using the Built-In Form Helper Methods ...................................................................................599
Creating Form Elements .................................................................................................................................... 599
Specifying the Route Used by a Form ................................................................................................................ 606
Using Input Helpers ........................................................................................................................................... 608
Creating Select Elements .................................................................................................................................. 613
Summary ...................................................................................................................................615
Chapter 22: Templated Helper Methods ■ ������������������������������������������������������������������������617
Preparing the Example Project ..................................................................................................617
Using Templated Helper Methods ..............................................................................................620
Generating Label and Display Elements ............................................................................................................ 624
Using Whole-Model Templated Helpers ............................................................................................................. 626
Using Model Metadata ..............................................................................................................629
Using Metadata to Control Editing and Visibility ................................................................................................ 630
Using Metadata for Labels ................................................................................................................................. 632
Using Metadata for Data Values ........................................................................................................................ 634
Using Metadata to Select a Display Template.................................................................................................... 635
Applying Metadata to a Buddy Class ................................................................................................................. 637
Working with Complex Type Properties ............................................................................................................. 639
Customizing the Templated View Helper System ......................................................................640
Creating a Custom Editor Template ................................................................................................................... 640
Creating a Generic Template .............................................................................................................................. 642
Replacing the Built-in Templates ....................................................................................................................... 643
Summary ...................................................................................................................................644
Chapter 23: URL and Ajax Helper Methods ■ ��������������������������������������������������������������������645
Preparing the Example Project ..................................................................................................646
Defining Additional CSS Styles .......................................................................................................................... 646
Installing the NuGet Packages ........................................................................................................................... 647
Creating Basic Links and URLs ..................................................................................................647
■ Contents
xxi
Using MVC Unobtrusive Ajax .....................................................................................................650
Creating the Synchronous Form View ............................................................................................................... 650
Preparing the Project for Unobtrusive Ajax ........................................................................................................ 651
Creating an Unobtrusive Ajax Form ...........................................................................................653
Preparing the Controller .................................................................................................................................... 653
Creating the Ajax Form ...................................................................................................................................... 655
Understanding How Unobtrusive Ajax Works ..................................................................................................... 657
Setting Ajax Options ..................................................................................................................657
Ensuring Graceful Degradation .......................................................................................................................... 658
Providing the User with Feedback While Making an Ajax Request .................................................................... 659
Prompting the User Before Making a Request .................................................................................................. 661
Creating Ajax Links ....................................................................................................................662
Ensuring Graceful Degradation for Links ........................................................................................................... 664
Working with Ajax Callbacks .....................................................................................................664
Working with JSON ...................................................................................................................667
Adding JSON Support to the Controller ............................................................................................................. 667
Processing JSON in the Browser ....................................................................................................................... 668
Preparing Data for Encoding .............................................................................................................................. 671
Detecting Ajax Requests in the Action Method .................................................................................................. 672
Summary ...................................................................................................................................675
Chapter 24: Model Binding ■ ��������������������������������������������������������������������������������������������677
Preparing the Example Project ..................................................................................................677
Understanding Model Binding ...................................................................................................680
Using the Default Model Binder .................................................................................................682
Binding to Simple Types .................................................................................................................................... 682
Binding to Complex Types .................................................................................................................................. 685
Binding to Arrays and Collections ...................................................................................................................... 692
Manually Invoking Model Binding .............................................................................................698
Dealing with Binding Errors ............................................................................................................................... 700
■ Contents
xxii
Customizing the Model Binding System ....................................................................................701
Creating a Custom Value Provider ..................................................................................................................... 701
Creating a Custom Model Binder ....................................................................................................................... 704
Registering the Custom Model Binder ............................................................................................................... 706
Summary ...................................................................................................................................707
Chapter 25: Model Validation ■ ����������������������������������������������������������������������������������������709
Preparing the Example Project ..................................................................................................710
Creating the Layout ........................................................................................................................................... 711
Creating the Views ............................................................................................................................................. 711
Explicitly Validating a Model ......................................................................................................713
Displaying Validation Errors to the User ............................................................................................................ 714
Displaying Validation Messages ................................................................................................716
Displaying Property-Level Validation Messages ................................................................................................ 720
Using Alternative Validation Techniques ....................................................................................721
Performing Validation in the Model Binder ........................................................................................................ 721
Specifying Validation Rules Using Metadata ..................................................................................................... 723
Defining Self-Validating Models ........................................................................................................................ 729
Performing Client-Side Validation .............................................................................................731
Enabling Client-Side Validation .......................................................................................................................... 731
Using Client-Side Validation .............................................................................................................................. 733
Understanding How Client-Side Validation Works ............................................................................................. 734
Performing Remote Validation ...................................................................................................735
Summary ..................................................................................................................................739
Chapter 26: Bundles ■ ������������������������������������������������������������������������������������������������������741
Preparing the Example Application ...........................................................................................741
Adding the NuGet Packages .............................................................................................................................. 741
Creating the Model and Controller ..................................................................................................................... 742
Creating the Layout and View ............................................................................................................................ 743
■ Contents
xxiii
Profiling Script and Style Sheet Loading ...................................................................................746
Using Script and Style Bundles .................................................................................................747
Adding the NuGet Package ................................................................................................................................ 748
Defining the Bundles ......................................................................................................................................... 748
Applying Bundles ............................................................................................................................................... 750
Optimizing the JavaScript and CSS Files ........................................................................................................... 752
Summary ...................................................................................................................................754
Chapter 27: Web API and Single-page Applications ■ ������������������������������������������������������755
Understanding Single-page Applications ..................................................................................755
Preparing the Example Application ...........................................................................................756
Creating the Model ............................................................................................................................................ 756
Adding the NuGet Packages .............................................................................................................................. 758
Adding the Controller ........................................................................................................................................ 759
Adding the Layout and Views ............................................................................................................................ 760
Setting the Start Location and Testing the Example Application ...................................................................... 762
Using Web API ...........................................................................................................................763
Creating the Web API Controller ......................................................................................................................... 763
Testing the API Controller .................................................................................................................................. 764
Understanding How the API Controller Works ...........................................................................765
Understanding API Controller Action Selection .................................................................................................. 767
Mapping HTTP Methods to Action Methods ....................................................................................................... 767
Using Knockout for Single-page Applications ...........................................................................768
Adding the JavaScript Libraries to the Layout ................................................................................................... 769
Implementing the Summary .............................................................................................................................. 770
Implementing the Create Feature ...................................................................................................................... 777
Completing the Application ......................................................................................................780
Simplify the Home Controller ............................................................................................................................ 781
Manage Content Visibility ................................................................................................................................. 781
Summary ...................................................................................................................................784
Index ���������������������������������������������������������������������������������������������������������������������������������785
xxv
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.
xxvii
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.