Steven Sanderson1430210079, 9781430210078
The ASP.NET MVC Framework is the latest evolution of Microsoft’s ASP.NET web platform. It introduces a radically new high–productivity programming model that promotes cleaner code architecture, test–driven development, and powerful extensibility, combined with all the benefits of ASP.NET 3.5.
An integral benefit of this book is that the core Model–View–Controller architectural concepts are not simply explained or discussed in isolation, but demonstrated in action. You’ll work through an extended tutorial to create a working e–commerce web application that combines ASP.NET MVC with the latest C# 3.0 language features and unit–testing best practices. By gaining this invaluable, practical experience, you can discover MVCs strengths and weaknesses for yourself—and put your best learned theory into practice.
What you’ll learn
– Gain a solid architectural background to ASP.NET MVC, including Model–View–Controller and REST concepts.
– Explore the ASP.NET MVC framework with detailed coverage of all aspects of the framework and the official MVC development toolkit.
– See how it works with test–driven development in action.
– Capitalize on your existing knowledge quickly and easily through translation and comparison of features in classic ASP.NET to those in ASP.NET MVC.
– Learn about the latest security and deployment issues, including IIS 7.0.
Who is this book for?
This book is for web developers with a basic knowledge of ASP.NET and C# who want, or need, to start using the new ASP.NET MVC framework.
About the Apress Pro Series
The Apress Pro series books are practical, professional tutorials to keep you on and moving up the professional ladder.
You have gotten the job, now you need to hone your skills in these tough competitive times. The Apress Pro series expands your skills and expertise in exactly the areas you need. Master the content of a Pro book, and you will always be able to get the job done in a professional development project. Written by experts in their field, Pro series books from Apress give you the hard–won solutions to problems you will face in your professional programming career.
Table of contents :
Prelims
……Page 1
Contents at a Glance……Page 7
Contents……Page 9
About the Author……Page 20
About the Technical Reviewer……Page 21
Acknowledgments……Page 22
Who This Book Is For……Page 23
Customer Support……Page 24
Contacting the Author……Page 25
Unknown……Page 0
SP.NET MVC is a radical shift for web developers using the Microsoft platform. This new framework emphasizes clean architecture,……Page 27
A Brief History of Web Development……Page 29
What’s Wrong with Traditional ASP.NET?……Page 30
Web Development Today……Page 31
Ruby on Rails……Page 32
Model-View-Controller Architecture……Page 33
Tight Control over HTML……Page 34
Built on the Best Parts of the ASP.NET Platform……Page 35
Who Should Use ASP.NET MVC?……Page 36
Comparisons with Ruby on Rails……Page 37
Comparisons with MonoRail……Page 38
Summary……Page 39
Preparing Your Workstation……Page 41
Creating a New ASP.NET MVC Project……Page 42
Removing Unnecessary Files……Page 44
How Does It Work?……Page 45
Creating and Rendering a View……Page 46
Adding Dynamic Output……Page 48
Linking Between Actions……Page 49
Adding a Model Class……Page 51
Building a Form……Page 52
Dude, Where’s My Data?……Page 53
Introducing Model Binding……Page 54
Introducing Strongly Typed Views……Page 55
Adding Validation……Page 57
Model Binding Tells Input Controls to Redisplay User-Entered Values……Page 58
Finishing Off……Page 59
Summary……Page 61
Understanding Model-View-Controller Architecture……Page 63
The Smart UI (Anti-Pattern)……Page 64
Model-View Architecture……Page 65
Three-Tier Architecture……Page 66
Model-View-Controller Architecture……Page 67
History and Benefits……Page 68
Model-View-Presenter……Page 69
An Example Domain Model……Page 70
Ubiquitous Language……Page 71
Aggregates and Simplification……Page 72
Keeping Data Access Code in Repositories……Page 74
Using LINQ to SQL……Page 75
WHAT’S A DATACONTEXT?……Page 76
Implementing the Auctions Domain Model……Page 77
Implementing the Auction Repositories……Page 80
Building Loosely Coupled Components……Page 82
Using Inversion of Control……Page 83
An MVC-Specific Example……Page 85
Meet Castle Windsor……Page 86
Getting Started with Automated Testing……Page 87
Unit Tests and Integration Tests……Page 89
The Red-Green Development Style……Page 90
So, Was It Worth It?……Page 93
Extension Methods……Page 94
Lambda Methods……Page 96
Automatic Properties……Page 97
Object and Collection Initializers……Page 98
Anonymous Types……Page 99
Putting It All Together……Page 100
Deferred Execution……Page 101
Using LINQ to Objects……Page 102
Lambda Expressions……Page 103
IQueryable and LINQ to SQL……Page 104
Summary……Page 106
SportsStore: A Real Application……Page 107
Getting Started……Page 108
Creating Your Solutions and Projects……Page 109
Creating an Abstract Repository……Page 111
Making a Fake Repository……Page 112
Removing Unnecessary Files……Page 113
Adding the First Controller……Page 114
Setting Up the Default Route……Page 115
Adding the First View……Page 116
Defining the Database Schema……Page 118
Setting Up LINQ to SQL……Page 120
Creating a Real Repository……Page 121
Creating a Custom Controller Factory……Page 123
Using Your IoC Container……Page 125
Choosing a Component Lifestyle……Page 127
Creating Automated Tests……Page 128
TESTING: GETTING STARTED……Page 129
Configuring a Custom URL Schema……Page 132
Adding a RouteTable Entry……Page 133
Displaying Page Links……Page 134
TESTING: DESIGNING THE PAGELINKS HELPER……Page 135
Making the HTML Helper Method Visible to All View Pages……Page 137
TESTING: PAGE NUMBERS AND PAGE COUNTS……Page 138
Defining Page Layout in the Master Page……Page 140
Adding CSS Rules……Page 141
Creating a Partial View……Page 143
Summary……Page 145
Adding Navigation Controls……Page 147
TESTING: FILTERING THE PRODUCTS LIST BY CATEGORY……Page 148
TESTING: UPDATING YOUR TESTS……Page 149
Implementing the Category Filter……Page 150
Defining a URL Schema for Categories……Page 151
TESTING: INBOUND ROUTE MAPPING……Page 152
TESTING: OUTBOUND URL GENERATION……Page 154
Building a Category Navigation Menu……Page 157
Creating the Navigation Controller……Page 158
TESTING: GENERATING THE LIST OF CATEGORY LINKS……Page 160
Selecting and Rendering a List of Category Links……Page 161
Highlighting the Current Category……Page 163
TESTING: SELECTING THE CORRECT NAVLINK TO HIGHLIGHT……Page 164
TESTING: UPDATING YOUR TESTS……Page 165
Building the Shopping Cart……Page 166
Defining the Cart Entity……Page 167
TESTING: SHOPPING CART BEHAVIOR……Page 168
Adding “Add to Cart” Buttons……Page 170
Multiple Tags……Page 171
ASP.NET MVC Offers a Tidier Way of Working with Session Storage……Page 172
Creating a Custom Model Binder……Page 173
TESTING: CARTCONTROLLER……Page 174
Implementing AddToCart and RemoveFromCart……Page 175
Displaying the Cart……Page 176
TESTING: CARTCONTROLLER’S INDEX ACTION……Page 177
Removing Items from the Cart……Page 179
Displaying a Cart Summary in the Title Bar……Page 180
Submitting Orders……Page 182
Enhancing the Domain Model……Page 183
TESTING: SHIPPING DETAILS……Page 184
Prompting the Customer for Shipping Details……Page 185
Completing CartController……Page 187
TESTING: ORDER SUBMISSION……Page 188
Adding a Fake Order Submitter……Page 190
Displaying Validation Errors……Page 191
Displaying a “Thanks for Your Order” Screen……Page 192
Implementing the EmailOrderSubmitter……Page 193
Exercise: Credit Card Processing……Page 194
Summary……Page 195
TESTING……Page 197
Creating AdminController: A Place for the CRUD Features……Page 198
TESTING: THE INDEX ACTION……Page 200
Rendering a Grid of Products in the Repository……Page 201
Implementing the List View Template……Page 202
TESTING: THE EDIT ACTION……Page 205
Creating a Product Editor UI……Page 206
TESTING: EDIT SUBMISSIONS……Page 207
Adding Validation……Page 210
Creating New Products……Page 212
TESTING: THE DELETE ACTION……Page 213
Securing the Administration Features……Page 214
Setting Up Forms Authentication……Page 215
Using a Filter to Enforce Authentication……Page 216
Displaying a Login Prompt……Page 217
BUT WHAT ABOUT TESTABILITY?……Page 220
Preparing the Domain Model and Database……Page 221
A Little-Known Fact About HTML Forms……Page 222
Displaying Product Images……Page 223
Summary……Page 225
o far, you’ve learned about why the ASP.NET MVC Framework exists, and have gained understanding of its architecture and underlyi……Page 227
Developing MVC Applications in Visual Studio……Page 229
The Default MVC Project Structure……Page 230
Naming Conventions……Page 233
Debugging MVC Applications and Unit Tests……Page 234
Launching the Visual Studio Debugger……Page 235
Attaching the Debugger to a Test Runner (e.g., NUnit GUI)……Page 236
Using the Debugger……Page 237
Stepping into the .NET Framework Source Code……Page 238
The Request Processing Pipeline……Page 239
Stage 1: IIS……Page 240
Finding and Invoking Controllers……Page 242
What Controllers Normally Do……Page 243
Rendering a View……Page 244
Summary……Page 245
Putting the Programmer Back in Control……Page 247
Setting Up Routes……Page 248
The Main Characters: RouteBase, Route, and RouteCollection……Page 250
How Routing Fits into the Request Processing Pipeline……Page 251
Adding a Route Entry……Page 252
Meet RouteValueDictionary……Page 253
Using Parameters……Page 254
Using Defaults……Page 255
Using Constraints……Page 256
Matching Against Regular Expressions……Page 257
Matching Custom Constraints……Page 258
Accepting a Variable-Length List of Parameters……Page 259
Using the RouteExistingFiles Flag……Page 260
Using IgnoreRoute to Bypass the Routing System……Page 261
Generating Outgoing URLs……Page 262
Passing Extra Parameters……Page 263
Generating Fully Qualified Absolute URLs……Page 264
Generating Links and URLs from Pure Routing Data……Page 265
Performing Redirections to Generated URLs……Page 266
Understanding the Outbound URL-Matching Algorithm……Page 267
THE CURRENT REQUEST’S PARAMETERS MAY BE REUSED……Page 268
Generating Hyperlinks with Html.ActionLink and Lambda Expressions……Page 269
Why You Might Not Want to Use Named Routes……Page 270
Testing Inbound URL Routing……Page 271
Using Test Doubles……Page 272
Using a Mocking Framework (Moq)……Page 273
Testing Outbound URL Generation……Page 275
Implementing a Custom RouteBase Entry……Page 277
Implementing a Custom Route Handler……Page 278
URL Schema Best Practices……Page 279
Make Your URLs Clean and Human-Friendly……Page 280
On Query Strings……Page 281
Use the Correct Type of HTTP Redirection……Page 282
Search Engine Optimization……Page 283
Summary……Page 284
An Overview……Page 285
All Controllers Implement IController……Page 286
The Controller Base Class……Page 287
Getting Data from Context Objects……Page 288
Parameters Objects Are Instantiated Using a Model Binder……Page 290
Invoking Model Binding Manually in an Action Method……Page 291
Understanding the ActionResult Concept……Page 292
Returning HTML by Rendering a View……Page 295
Passing a ViewData Dictionary and a Model Object……Page 296
Performing Redirections……Page 299
Redirecting to a Different Action Method……Page 300
Using TempData to Preserve Data Across a Redirection……Page 301
HOW THE TEMPDATA STORE COMPARES TO THE SESSION STORE……Page 302
Returning Textual Data……Page 303
Generating an RSS Feed……Page 304
Returning JavaScript Commands……Page 305
Returning Files and Binary Data……Page 306
Sending a File Directly from Disk……Page 307
Example: Watermarking an Image (and the Concept of Testability Seams)……Page 309
Introducing the Four Basic Types of Filters……Page 312
Applying Filters to Controllers and Action Methods……Page 314
Creating Action Filters and Result Filters……Page 315
Controlling the Order of Execution……Page 317
Using the Controller Itself As a Filter……Page 318
Creating and Using Authorization Filters……Page 319
How Authorization Filters Interact with Output Caching……Page 320
Creating a Custom Authorization Filter……Page 321
Using HandleErrorAttribute……Page 322
Creating a Custom Exception Filter……Page 324
Bubbling Exceptions Through Action and Result Filters……Page 325
The [OutputCache] Action Filter……Page 326
Other Built-In Filter Types……Page 328
Working with DefaultControllerFactory……Page 329
Prioritizing Namespaces on Individual Route Entries……Page 330
Creating a Custom Controller Factory……Page 331
Customizing How Action Methods Are Selected and Invoked……Page 332
Using [ActionName] to Specify a Custom Action Name……Page 333
Method Selection: Controlling Whether a C# Method Should Agree to Handle a Request……Page 334
How the Whole Method Selection Process Fits Together……Page 336
Handling Unknown Actions……Page 337
Testing Controllers and Actions……Page 338
Testing a Choice of View and ViewData……Page 339
Testing ViewData Values……Page 340
Testing Redirections……Page 341
Mocking Context Objects……Page 342
A Reusable ASP.NET MVC Mocking Helper……Page 344
Summary……Page 346
How Views Fit into ASP.NET MVC……Page 347
The WebForms View Engine……Page 348
Five Ways to Add Dynamic Content to a View Template……Page 349
Using Inline Code……Page 350
Understanding How MVC Views Actually Work……Page 352
Understanding How ASPX Templates Are Compiled……Page 353
Understanding ViewData……Page 355
Rendering ViewData Items Using ViewData.Eval……Page 356
Using ViewData.Eval to Simplify Inline Expressions……Page 357
Using HTML Helper Methods……Page 358
Rendering Input Controls……Page 359
Rendering Links and URLs……Page 361
Rendering Drop-Down Lists and Multiselect Lists……Page 362
Bonus Helper Methods in Microsoft.Web.Mvc.dll……Page 364
Other HTML Helpers……Page 365
Rendering Form Tags……Page 366
Creating Your Own HTML Helper Methods……Page 368
Attaching Your Helper Method to HtmlHelper via an Extension Method……Page 369
Creating a Partial View……Page 370
Passing ViewData to a Partial View……Page 371
Passing an Explicit ViewData.Model Object to a Partial View……Page 372
Passing an Explicit ViewData.Model Object to the Control……Page 375
Using Html.RenderAction to Create Reusable Widgets with Application Logic……Page 377
When It’s Appropriate to Use Html.RenderAction……Page 378
Creating a Widget Based on Html.RenderAction……Page 379
Sharing Page Layouts Using Master Pages……Page 381
Method 1: Have Your Controller Put a Control-Specific Data Item into ViewData……Page 382
Method 3: Use Html.RenderAction……Page 383
Step 1: Implement IViewEngine, or Derive a Class from VirtualPathProviderViewEngine……Page 384
Step 2: Implement IView……Page 385
Step 3: Use It……Page 386
Step 4: Register Your View Engine with the Framework……Page 388
Using the NVelocity View Engine……Page 389
Using the Brail View Engine……Page 391
Using the Spark View Engine……Page 392
Using the NHaml View Engine……Page 393
Summary……Page 394
Model Binding……Page 395
Model-Binding to Action Method Parameters……Page 396
Model-Binding to Custom Types……Page 397
Omitting a Prefix……Page 398
Choosing a Subset of Properties to Bind……Page 399
Invoking Model Binding Directly……Page 400
Dealing with Model-Binding Errors……Page 401
Model-Binding to Arrays, Collections, and Dictionaries……Page 402
Model-Binding Collections of Custom Types……Page 403
Creating a Custom Model Binder……Page 404
Configuring Which Model Binders Are Used……Page 406
Using Model Binding to Receive File Uploads……Page 407
Registering Errors in ModelState……Page 409
View Helpers for Displaying Error Information……Page 412
How the Framework Maintains State in Input Controls……Page 414
Performing Validation During Model Binding……Page 415
Moving Validation Logic into Your Model Layer……Page 416
Implementing Validation on Model Operations……Page 417
Implementing Sophisticated Rules……Page 420
Generating Client-Side Validation from Model Attributes……Page 421
Wizards and Multistep Forms……Page 422
Navigation Through Multiple Steps……Page 423
Collecting and Preserving Data……Page 425
Completing the Wizard……Page 428
Validation……Page 429
VIEWSTATE AND SERIALIZATION……Page 431
Implementing a CAPTCHA……Page 432
Creating an HTML Helper Method……Page 434
Rendering a Dynamic Image……Page 436
Distorting the Text……Page 438
Verifying the Form Submission……Page 439
Confirmation Links and Tamper-Proofing with HMAC Codes……Page 440
An HMAC Utility Class……Page 441
Usage Example……Page 443
Summary……Page 444
Why You Should Use a JavaScript Toolkit……Page 445
ASP.NET MVC’s Ajax Helpers……Page 446
Fetching Page Content Asynchronously Using Ajax.ActionLink……Page 447
Passing Options to Ajax.ActionLink……Page 450
Running JavaScript Functions Before or After Asynchronous Requests……Page 451
Detecting Asynchronous Requests……Page 452
Submitting Forms Asynchronously Using Ajax.BeginForm……Page 453
Invoking JavaScript Commands from an Action Method……Page 454
Reviewing ASP.NET MVC’s Ajax Helpers……Page 456
Referencing jQuery……Page 457
INTELLISENSE SUPPORT FOR JQUERY……Page 458
Basic jQuery Theory……Page 459
A QUICK NOTE ABOUT ELEMENT IDS……Page 460
Event Handling……Page 461
Global Helpers……Page 462
Unobtrusive JavaScript……Page 463
Adding Client-Side Interactivity to an MVC View……Page 464
Improvement 1: Zebra-Striping……Page 465
Improvement 2: Confirm Before Deletion……Page 466
Improvement 3: Hiding and Showing Sections of the Page……Page 467
Ajax-Enabling Links and Forms……Page 468
Hijaxing Links……Page 469
Hijaxing Forms……Page 473
Client/Server Data Transfer with JSON……Page 475
Fetching XML Data Using jQuery……Page 478
Animations and Other Graphical Effects……Page 479
Example: A Sortable List……Page 480
Implementing Client-Side Validation with jQuery……Page 482
Summary……Page 484
All Input Can Be Forged……Page 485
HOW DOES HTTP WORK?……Page 486
Forging HTTP Requests……Page 487
Cross-Site Scripting and HTML Injection……Page 489
Defense……Page 490
ASP.NET’s Request Validation Feature……Page 491
Request Validation: Good or Bad?……Page 492
Filtering HTML Using the HTML Agility Pack……Page 493
Session Hijacking……Page 494
Defense by Setting the HttpOnly Flag on Cookies……Page 495
Cross-Site Request Forgery……Page 496
Defense……Page 497
Preventing CSRF Using the Anti-Forgery Helpers……Page 498
SQL Injection……Page 499
Defense Using Parameterized Queries……Page 500
Don’t Expose Action Methods Accidentally……Page 501
Summary……Page 502
Server Requirements……Page 503
Understanding Web Sites and Virtual Directories……Page 504
How Requests Are Handled by IIS 5, IIS 6, and IIS 7 in Classic Pipeline Mode……Page 506
How Requests Are Handled in IIS 7 Integrated Pipeline Mode……Page 508
Deploying Your Application……Page 509
Deploying the ASP.NET MVC and Routing Assemblies……Page 510
Using Visual Studio 2008’s Publish Feature……Page 511
Making It Work on Windows Server 2003/IIS 6……Page 512
Adding and Configuring a New MVC Web Site in IIS Manager……Page 513
Making Extensionless URLs Work on IIS 6……Page 515
Making It Work on IIS 7……Page 520
Adding and Configuring a New MVC Web Site in IIS 7……Page 521
Supporting Changeable Routing Configurations……Page 523
Using ASP.NET’s Configuration Facilities……Page 524
Configuring Arbitrary Key/Value Pairs……Page 525
Configuring Arbitrary Data Structures……Page 526
Controlling Compilation on the Server……Page 528
Summary……Page 529
ASP.NET Platform Features……Page 531
Windows Authentication……Page 532
Preventing or Limiting Anonymous Access……Page 534
Forms Authentication……Page 535
Setting Up Forms Authentication……Page 536
Handling Login Attempts……Page 538
Using Cookieless Forms Authentication……Page 539
Membership, Roles, and Profiles……Page 540
Setting Up SqlMembershipProvider……Page 542
Managing Members Using the Web Administration Tool……Page 545
Using a Membership Provider with Forms Authentication……Page 546
Creating a Custom Membership Provider……Page 547
Setting Up and Using Roles……Page 548
Using the Built-In SqlRoleProvider……Page 549
Creating a Custom Role Provider……Page 550
Using the Built-In SqlProfileProvider……Page 551
Configuring, Reading, and Writing Profile Data……Page 552
Creating a Custom Profile Provider……Page 553
URL-Based Authorization……Page 555
Reading and Writing Cache Data……Page 556
Using Advanced Cache Features……Page 559
Site Maps……Page 560
Setting Up and Using Site Maps……Page 561
Creating a Custom Navigation Control with the Site Maps API……Page 562
Generating Site Map URLs from Routing Data……Page 564
Using Security Trimming……Page 565
Internationalization……Page 566
Setting Up Internationalization……Page 567
Tips for Working with Resource Files……Page 570
Using Placeholders in Resource Strings……Page 571
HTTP Compression……Page 572
Tracing and Monitoring……Page 574
Monitoring Page Generation Times……Page 575
Monitoring LINQ to SQL Database Queries……Page 576
Summary……Page 580
Using WebForms Technologies in an MVC Application……Page 581
Using WebForms Controls in MVC Views……Page 582
Using WebForms Pages in an MVC Web Application……Page 584
Adding Routing Support for WebForms Pages……Page 585
Passing Parameters (and Model Binding) to WebForms Pages……Page 587
A Note About URL-Based Authorization……Page 588
Using ASP.NET MVC in a WebForms Application……Page 589
Upgrading an ASP.NET WebForms Application to Support MVC……Page 590
Getting Visual Studio to Offer MVC Items……Page 594
Interactions Between WebForms Pages and MVC Controllers……Page 595
Transferring Data Between MVC and WebForms……Page 596
Summary……Page 597
Index……Page 599
Reviews
There are no reviews yet.