ASP.NET MVC 4 in Action a Revised Edition of ASP.NET MVC 2 in Action
Total Page:16
File Type:pdf, Size:1020Kb
ASP.NE IN ACTION Jeffrey Palermo Jimmy Bogard Eric Hexter Matthew Hinze Jeremy Skinner FOREWORD BY Phil Haack MANNING www.it-ebooks.info Praise for Earlier Editions of ASP.NET MVC in Action An authoritative source on ASP.NET MVC 2. Pick up this book! —Alessandro Gallo, Microsoft MVP ASP.NET MVC 2 in Action is a good read and an invaluable reference. —Derek Jackson, Software Architect, Harvard-Westlake Learn MVC 2 from the people who helped shape it. Get ready for even more MVC action in this excellent sequel. —Alex Thissen, Killer-Apps Hands-down the best MVC resource available! Written by the industry’s best and it shows…so good you may need to buy two copies. —Andrew Siemer, Software Architect, Lamps Plus Fully explains fundamental MVC concepts and best development practices. —Tetsuo Torigai, Developer, Torigai Consulting This book doesn’t just explain how to use Microsoft’s MVC—it teaches practices that help developers create more maintainable projects. —Anne Epstein, Senior Consultant, Headspring ASP.NET in Action is a must-read for anyone who is serious about developing with the ASP.NET MVC framework. —Steve Michelotti, Microsoft MVP, geekswithblogs.net At merely 300 pages, ASP.NET MVC in Action is a true masterpiece…. The authors are all considered rock stars in the ASP.NET community and they have opened the doors to their concert with ASP.NET MVC in Action. —Mohammad Azam, Microsoft MVP www.it-ebooks.info Praise for Earlier Editions of ASP.NET MVC in Action This book does a good job of not only showing you what to do, it also provides cautionary words to avoid poor practices that may lead to maintenance issues on non-trivial applications. —Venkat Subramanian, NoFluffJustStuff Blogs I really enjoyed ASP.NET MVC in Action and highly recommend it for a fresh look at the ASP.NET MVC framework. —David Hayden, Microsoft MVP ASP.NET MVC in Action will guide you from your first project through advanced topics such as AJAX and deploying on suboptimal hosting environments. The writing style is clear and concise. Diagrams and code examples are abundant. I recommend it for anyone looking for a great resource for learning about or becoming a better user of the ASP.NET MVC framework. —Nathan Stott, Partner and Software Engineer, Whiteboard-IT I’m very happy with this book. I would definitely recommend it to anyone interested in ASP.NET MVC. Getting beyond the text that comes with the CodeCampServer is just icing on the cake. —Chris Stewart, CompiledMonkey.com The authors not only did an excellent job of putting together a great practical guide to ASP.NET MVC, they also successfully embedded some subversive ALT.NET concepts that will make us all better developers. And at the end of the day, that is a damn fine accomplishment! —Bobby Johnson, AppExtremes As my first introduction to MVC, I found this book very readable and interesting. —Roger Wright, Engineering Manager, Aha Macav Power Service www.it-ebooks.info ASP.NET MVC 4 in Action A revised edition of ASP.NET MVC 2 in Action JEFFREY PALERMO, JIMMY BOGARD ERIC HEXTER, MATTHEW HINZE AND JEREMY SKINNER MANNING Shelter Island www.it-ebooks.info For online information and ordering of this and other Manning books, please visit www.manning.com. The publisher offers discounts on this book when ordered in quantity. For more information, please contact Special Sales Department Manning Publications Co. 20 Baldwin Road PO Box 261 Shelter Island, NY 11964 Email: [email protected] ©2012 by Manning Publications Co. All rights reserved. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by means electronic, mechanical, photocopying, or otherwise, without prior written permission of the publisher. Many of the designations used by manufacturers and sellers to distinguish their products are claimed as trademarks. Where those designations appear in the book, and Manning Publications was aware of a trademark claim, the designations have been printed in initial caps or all caps. Recognizing the importance of preserving what has been written, it is Manning’s policy to have the books we publish printed on acid-free paper, and we exert our best efforts to that end. Recognizing also our responsibility to conserve the resources of our planet, Manning books are printed on paper that is at least 15 percent recycled and processed without the use of elemental chlorine. Manning Publications Co. Development editor: Cynthia Kane 20 Baldwin Road Technical proofreader: Javier Lozano PO Box 261 Copyeditor: Andy Carroll Shelter Island, NY 11964 Proofreader: Maureen Spencer Cover designer: Marija Tudor Typesetter: Gordan Salinovic ISBN 9781617290411 Printed in the United States of America 1 2 3 4 5 6 7 8 9 10 – MAL – 17 16 15 14 13 12 www.it-ebooks.info brief contents PART 1 HIGH-SPEED FUNDAMENTALS .........................................1 1 ■ Introduction to ASP.NET MVC 3 2 ■ Hello MVC world 12 3 ■ View fundamentals 38 4 ■ Action-packed controllers 59 PART 2 WORKING WITH ASP.NET MVC..................................79 5 ■ View models 81 6 ■ Validation 92 7 ■ Ajax in ASP.NET MVC 104 8 ■ Security 135 9 ■ Controlling URLs with routing 153 10 ■ Model binders and value providers 185 11 ■ Mapping with AutoMapper 197 12 ■ Lightweight controllers 207 13 ■ Organization with areas 220 14 ■ Third-party components 232 15 ■ Data access with NHibernate 244 v www.it-ebooks.info vi BRIEF CONTENTS PART 3 MASTERING ASP.NET MVC ......................................265 16 ■ Extending the controller 267 17 ■ Advanced view techniques 276 18 ■ Dependency injection and extensibility 294 19 ■ Portable areas 311 20 ■ Full system testing 321 21 ■ Hosting ASP.NET MVC applications 339 22 ■ Deployment techniques 365 23 ■ Upgrading to ASP.NET MVC 4 374 24 ■ ASP.NET Web API 385 www.it-ebooks.info contents foreword xv foreword to the second edition xvi foreword to the first edition xvii preface xix acknowledgments xxiii about this book xxvi about the authors xxix about the cover illustration xxxii PART 1 HIGH-SPEED FUNDAMENTALS..............................1 Introduction to ASP.NET MVC 3 1 1.1 Setting the stage 4 The .NET platform 4 ■ ASP.NET Web Forms 5 1.2 What is ASP.NET MVC? 5 The MVC pattern 7 ■ Benefits of ASP.NET MVC 8 1.3 What’s new in ASP.NET MVC 3/4? 8 The Razor view engine 9 ■ Package management with NuGet 9 Improved extensibility 10 ■ Global action filters 10 ■ Dynamic language features 10 ■ Partial page output caching 10 Ajax improvements 10 ■ Validation improvements 10 1.4 Summary 11 vii www.it-ebooks.info viii CONTENTS Hello MVC world 12 2 2.1 Setting up your development environment 13 Installing MVC using the Web Platform Installer 13 2.2 Creating your first MVC application 15 Creating a new project 15 ■ A tour of the default project template 17 Controllers, actions, and displaying dynamic content 19 2.3 The Guestbook sample application 23 Creating the database 23 ■ Adding the model 24 ■ Accepting guestbook entries 28 ■ Displaying guestbook entries 33 Customizing the look and feel with layouts 35 2.4 Summary 37 View fundamentals 38 3 3.1 Introducing views 38 Selecting a view to render 39 ■ Overriding the view name 40 3.2 Passing data to views 40 Examining the ViewDataDictionary 40 ■ The ViewBag 42 Strongly typed views with a view model 43 ■ Displaying view model data in a view 44 3.3 Using strongly typed templates 48 EditorFor and DisplayFor templates 49 ■ Built-in templates 51 Selecting templates 52 ■ Customizing templates 54 3.4 Summary 58 Action-packed controllers 59 4 4.1 Exploring controllers and actions 60 IController and the controller base classes 60 ■ What makes an action method 62 4.2 What should be in an action method? 63 Manually mapping view models 64 ■ Input validation 66 4.3 Introduction to unit testing 69 Using the provided test project 69 ■ Testing the GuestbookController 71 4.4 Summary 77 www.it-ebooks.info CONTENTS ix PART 2 WORKING WITH ASP.NET MVC ......................79 View models 81 5 5.1 What is a view model? 82 The online store example 82 ■ Building the view model 84 Delivering the presentation model 84 ■ ViewData.Model 85 5.2 Representing user input 86 Designing the model 86 ■ Presenting the input model in a view 87 ■ Working with the submitted input 88 5.3 More complex models for both display and input 89 Designing a combined display and input model 90 ■ Working with the input model 90 5.4 Summary 91 Validation 92 6 6.1 Server-side validation 93 Validation with Data Annotations 93 ■ Extending the ModelMetadataProvider 96 6.2 Client-side validation 98 Getting started with client-side validation 99 ■ Using RemoteAttribute 100 ■ Creating custom client-side validators 101 6.3 Summary 103 Ajax in ASP.NET MVC 104 7 7.1 Ajax with jQuery 105 jQuery primer 106 ■ Using jQuery to make Ajax requests 107 Progressive enhancement 109 ■ Using Ajax to submit form data 111 7.2 ASP.NET MVC Ajax helpers 114 Ajax.ActionLink 116 ■ Ajax.BeginForm 117 ■ Ajax options 118 Differences from earlier versions of ASP.NET MVC 119 7.3 Ajax with JSON and client templates 120 Ajax with JSON 120 ■ Client-side templates 124 ■ Finishing touches 126 7.4 Creating an autocomplete text box 129 Building the CitiesController 129 7.5 Summary 134 www.it-ebooks.info x CONTENTS Security 135 8 8.1 Authentication and authorization 136 Restricting access with the AuthorizeAttribute 136 AuthorizeAttribute—how it works 138 8.2 Cross-site scripting (XSS) 140 XSS in action 140 ■ Avoiding XSS vulnerabilities 142 8.3 Cross-site request forgery (XSRF) 145 XSRF in action 146 ■ Preventing XSRF 147