BOOKS FOR PROFESSIONALS BY PROFESSIONALS® THE EXPERT’S VOICE® IN .NET Freeman Pro ASP.NET MVC 4 RELATED The ASP.NET MVC 4 Framework is the latest evolution of Microsoft’s ASP.NET web platform. It provides a high-productivity programming model that promotes cleaner code architecture, test-driven development, and powerful extensibility, combined with all the benefits of ASP.NET. In this fourth edition of Pro ASP.NET MVC 4, the core model-view-controller (MVC) archi- tectural concepts are not simply explained or discussed in isolation, but are demonstrated in action. You’ll work through an extended tutorial to create a working e-commerce web applica- tion that combines ASP.NET MVC with the latest C# language features and unit-testing best practices. By gaining this invaluable, practical experience, you’ll discover MVC’s strengths and weaknesses for yourself—and put your best-learned theory into practice. With Pro ASP.NET MVC 4, you’ll: • Gain a solid understanding of ASP.NET MVC 4, including the MVC pattern • Explore the entire ASP.NET MVC Framework in detail • See how MVC applications and test-driven development work in action • Capitalize on your existing knowledge quickly and easily through comparison of features in classic ASP.NET to those in ASP.NET MVC ASP.NET MVC 4 contains a number of significant advances over previous versions, and this book shows you the best way to apply these new features. Turn to Pro ASP.NET MVC 4 and start using this high-productivity programming model that promotes cleaner code architecture, test-driven development, and powerful extensibility. The book’s author, Adam Freeman has watched the growth of ASP.NET MVC since its first release. Adam started designing and building web applications 15 years ago and has been responsible for some of the world’s largest and most ambitious projects. US $54.99 Shelve in .NET User level: FOURTH Intermediate–Advanced EDITION SOURCE CODE ONLINE www.apress.com > m o ok.c o b e w o w w. w w < ok o B e w! o W m d fro For your convenience Apress has placed some of the front a nlo matter material after the index. Please use the Bookmarks w o D and Contents at a Glance links to access them. Contents at a Glance ■ Contents ................................................................................................................... vii ■ About the Author ..................................................................................................... xxi ■ About the Technical Reviewer ................................................................................ xxii ■ Acknowledgments ................................................................................................. xxiii ■Part 1: Introducing ASP.NET MVC 4 ............................................................................. 1 ■ Chapter 1: What’s the Big Idea? ................................................................................. 3 ■ Chapter 2: Your First MVC Application ..................................................................... 15 ■ Chapter 3: The MVC Pattern ..................................................................................... 47 ■ Chapter 4: Essential Language Features .................................................................. 73 ■ Chapter 5: Working with Razor .............................................................................. 101 ■ Chapter 6: Essential Tools for MVC ........................................................................ 125 ■ Chapter 7: SportsStore—A Real Application .......................................................... 161 ■ Chapter 8: SportsStore: Navigation ........................................................................ 201 ■ Chapter 9: SportsStore: Completing the Cart ......................................................... 231 ■ Chapter 10: SportsStore: Administration ............................................................... 255 ■ Chapter 11: SportsStore: Security & Finishing Touches ........................................ 283 ■ Part 2: ASP.NET MVC 4 in Detail ............................................................................. 301 ■ Chapter 12: Overview of MVC Projects ................................................................... 303 ■ Chapter 13: URL Routing ........................................................................................ 323 v ■ CONTENTS AT A GLANCE ■ Chapter 14: Advanced Routing Features ................................................................ 363 ■ Chapter 15: Controllers and Actions ...................................................................... 391 ■ Chapter 16: Filters .................................................................................................. 419 ■ Chapter 17: Controller Extensibility ....................................................................... 455 ■ Chapter 18: Views .................................................................................................. 485 ■ Chapter 19: Helper Methods ................................................................................... 511 ■ Chapter 20: Templated Helper Methods ................................................................. 541 ■ Chapter 21: URL and Ajax Helper Methods ............................................................. 569 ■ Chapter 22: Model Binding ..................................................................................... 599 ■ Chapter 23: Model Validation ................................................................................. 629 ■ Chapter 24: Bundles and Display Modes ................................................................ 657 ■ Chapter 25: Web API ............................................................................................... 679 ■ Chapter 26: Deployment ......................................................................................... 699 ■ Index ....................................................................................................................... 717 vi P A R T 1 Introducing ASP.NET MVC 4 ASP.NET MVC is a radical shift for web developers using the Microsoft platform. It emphasizes clean architecture, design patterns, and testability, and it doesn’t try to conceal how the Web works. The first part of this book is designed to help you understand broadly the foundational ideas of ASP.NET MVC, including the new features in ASP.NET MVC 4, and to experience in practice what the framework is like to use. CHAPTER 1 What’s the Big Idea? ASP.NET MVC is a Web development framework from Microsoft that combines the effectiveness and tidiness of model-view-controller (MVC) architecture, the most up-to-date ideas and techniques from agile development, and the best parts of the existing ASP.NET platform. It’s a complete alternative to traditional ASP.NET Web Forms, delivering considerable advantages for all but the most trivial of Web development projects. In this chapter, you’ll learn why Microsoft originally created ASP.NET MVC, how it compares to its predecessors and alternatives, and, finally, what’s new in ASP.NET MVC 4. A Brief History of Web Development To understand the distinctive aspects and design goals of ASP.NET MVC, it’s worth considering the history of Web development so far—brief though it may be. Over the years, Microsoft’s Web development platforms have demonstrated increasing power and, unfortunately, increasing complexity. As shown in Table 1-1, each new platform tackled the specific shortcomings of its predecessor. Table 1-1. Microsoft’s Lineage of Web Development Technologies Period Technology Strengths Weaknesses Jurassic Common Gateway Interface Simple Runs outside the Web (CGI)* server, so is resource- Flexible intensive (spawns a Only option at the time separate operating system process per request) Low-level Bronze age Microsoft Internet Database Runs inside Web server Just a wrapper for SQL Connector (IDC) queries and templates for formatting result sets 1996 Active Server Pages (ASP) General purpose Interpreted at runtime Encourages “spaghetti code” 3 CHAPTER 1 WHAT’S THE BIG IDEA? Period Technology Strengths Weaknesses 2002/03 ASP.NET Web Forms 1.0/1.1 Compiled Heavy on bandwidth “Stateful” UI Ugly HTML Vast infrastructure Untestable Encourages object- oriented programming 2005 ASP.NET Web Forms 2.0 2007 ASP.NET AJAX 2008 ASP.NET Web Forms 3.5 2009 ASP.NET MVC 1.0 2010 ASP.NET MVC 2.0 ASP.NET Web Forms 4.0 2011 ASP.NET MVC 3.0 2012 ASP.NET MVC 4.0 ASP.NET Web Forms 4.5 *CGI is a standard means of connecting a Web server to an arbitrary executable program that returns dynamic content. The specification is maintained by the National Center for Supercomputing Applications (NCSA). Traditional ASP.NET Web Forms ASP.NET was a huge shift when it first arrived in 2002. Figure 1-1 illustrates Microsoft’s technology stack as it appeared then. Figure 1-1. The ASP.NET Web Forms technology stack 4 CHAPTER 1 WHAT’S THE BIG IDEA? With Web Forms, Microsoft attempted to hide both HTTP (with its intrinsic statelessness) and HTML (which at the time was unfamiliar to many developers) by modeling the user interface (UI) as a hierarchy of server-side control objects. Each control kept track of its own state across requests (using the View State facility), rendering itself as HTML when needed and automatically connecting client-side events (for example, a button click) with the corresponding server-side event handler code. In effect, Web Forms is a giant abstraction layer designed to deliver a classic event-driven graphical user interface (GUI) over the Web. The idea was to make Web development feel just the same as Windows Forms development. Developers no longer needed to work with a series of independent HTTP requests and responses; we could now think in terms of a stateful UI. We could forget about the Web and its stateless nature, and instead build UIs using a drag-and-drop designer, and imagine—or at least pretend—that everything was happening on the server. What Is Wrong with ASP.NET Web Forms? Traditional ASP.NET Web Forms development was great in principle, but reality proved more complicated. Over time, the use of Web Forms in real-world projects highlighted some shortcomings: • View State weight: The actual mechanism for maintaining state across requests (known as View State) results in large blocks of data being transferred between the client and server. This data can reach hundreds of kilobytes in even modest Web applications, and it goes back and forth with every request, leading to slower response times and increasing the bandwidth demands of the server. • Page life cycle: The mechanism for connecting client-side events with server-side event handler code, part of the page life cycle, can be extraordinarily complicated and delicate. Few developers have success manipulating the control hierarchy at runtime without getting View State errors or finding that some event handlers mysteriously fail to execute. • False sense of separation of concerns: ASP.NET’s code-behind model provides a means to take application code out of its HTML markup and into a separate code- behind class. This has been widely applauded for separating logic and presentation, but, in reality, developers are encouraged to mix presentation code (for example, manipulating the server-side control tree) with their application logic (for example, manipulating database data) in these same monstrous code-behind classes. The end result can be fragile and unintelligible. • Limited control over HTML: Server controls render themselves as HTML, but not necessarily the HTML you want. In early version of ASP.NET 4 the HTML output failed to meet with Web standards or make good use of Cascading Style Sheets (CSS), and server controls generated unpredictable and complex ID attribute values that are hard to access using JavaScript. These problems are much improved in in ASP.NET 4 and ASP.NET 4.5, but it can still be tricky to get the HTML you expect. • Leaky abstraction: Web Forms tries to hide away HTML and HTTP wherever possible. As you try to implement custom behaviors, you frequently fall out of the abstraction, which forces you to reverse-engineer the postback event mechanism or perform obtuse acts to make it generate the desired HTML. Plus, all this abstraction can act as a frustrating barrier for competent Web developers. • Low testability: The designers of ASP.NET could not have anticipated that automated testing would become an essential component of software development. Not surprisingly, the tightly coupled architecture they designed is unsuitable for unit testing. Integration testing can be a challenge, too. 5 CHAPTER 1 WHAT’S THE BIG IDEA? ASP.NET has kept moving. Version 2.0 added a set of standard application components that can reduce the amount of code you need to write yourself. The AJAX release in 2007 was Microsoft’s response to the Web 2.0/AJAX frenzy of the day, supporting rich client-side interactivity while keeping developers’ lives simple. Things improved a lot with the ASP.NET 4 release, which embraced Web standard in a serious way for the first time. The most recent release, ASP.NET 4.5, actually takes some of the features from ASP.NET MVC and applies them to the Web Forms world, which addresses some of the more troublesome issues—but, even so, many of the intrinsic limitations remain. Web Development Today Outside Microsoft, Web development technology has been progressing rapidly and in several different directions since Web Forms was first released. Aside from AJAX, there have been other major developments. Web Standards and REST The drive for Web standards compliance has increased in recent years. Web sites are consumed on a greater variety of devices and browsers than ever before, and Web standards (for HTML, CSS, JavaScript, and so forth) remain our one great hope for enjoying a decent browsing experience everywhere—even on the Internet-enabled refrigerator. Modern Web platforms can’t afford to ignore the business case and the weight of developer enthusiasm for Web standards compliance. HTML5 is starting to enter mainstream use and provides the Web developer with rich capabilities that allow the client to perform work that was previously the exclusive responsibility of the server. These new capabilities and the increasing maturity of JavaScript libraries such as jQuery, jQuery UI, and jQuery Mobile means that standards have become ever more important and form the critical foundation for ever richer Web apps. Note We touch on HTML5, jQuery, and its cousins in this book, but we don’t go into depth, because these are topics in their own right. If you want more complete coverage, then Apress publishes Adam’s books on these subjects: Pro jQuery, Pro JavaScript for Web Apps, and The Definitive Guide to HTML5. At the same time, Representational State Transfer (REST) has become the dominant architecture for application interoperability over HTTP, completely overshadowing SOAP (the technology behind ASP.NET’s original approach to Web services). REST describes an application in terms of resources (URIs) representing real-world entities and standard operations (HTTP methods) representing available operations on those resources. For example, you might PUT a new http://www.example.com/Products/Lawnmower or DELETE http://www.example.com/Customers/Arnold- Smith. Today’s Web applications don’t serve just HTML; often they must also serve JSON or XML data to various client technologies including AJAX, Silverlight, and native smartphone applications. This happens naturally with REST, which eliminates the historical distinction between Web services and Web applications—but requires an approach to HTTP and URL handling that has not easily been supported by ASP.NET Web Forms. 6 CHAPTER 1 WHAT’S THE BIG IDEA? Agile and Test-Driven Development It is not just Web development that has moved on in the last decade—software development as a whole has shifted toward agile methodologies. This can mean a lot of different things, but it is largely about running software projects as adaptable processes of discovery and resisting the encumbrance and restrictions of excessive forward planning. Enthusiasm for agile methodologies tends to go hand-in-hand with a particular set of development practices and tools (usually open source) that promote and assist these practices. Test-driven development (TDD), and its latest incarnation, behavior-driven development (BDD), are two obvious examples. The idea is to design your software by first describing examples of desired behaviors (known as tests or specifications), so at any time you can verify the stability and correctness of your application by executing your suite of specifications against the implementation. There’s no shortage of .NET tools to support TDD/BDD, but these tend to not work well with Web Forms: • Unit testing tools let you specify the behavior of individual classes or other small code units in isolation. These can be effectively applied only to software that has been designed as a set of independent modules, so that each test can be run in isolation. Unfortunately, few Web Forms applications can be tested this way. Following the framework’s guidance to put logic into event handlers or even use server controls that directly query databases, developers typically end up tightly coupling their own application logic to the Web Forms runtime environment. This is death for unit testing. • UI automation tools let you simulate a series of user interactions against a complete running instance of your application. In theory, these can be used with Web Forms, but they can break down whenever you make a slight change to your page layout. Without special attention, Web Forms starts generating totally different HTML structures and element IDs, rendering your existing test suite useless. The .NET open source and independent software vendor (ISV) community has produced no end of top-quality unit testing frameworks (NUnit and xUnit), mocking frameworks (Moq and Rhino Mocks), inversion-of-control containers (Ninject and AutoFac), continuous integration servers (Cruise Control and TeamCity), object-relational mappers (NHibernate and Subsonic), and the like. Proponents of these tools and techniques have found a common voice, publishing and organizing conferences under the shared brand ALT.NET. Traditional ASP.NET Web Forms is not amenable to these tools and techniques because of its monolithic design, so from this vocal group of experts and industry thought leaders, Web Forms gets little respect. Ruby on Rails In 2004, Ruby on Rails was a quiet, open source contribution from an unknown player. Suddenly fame hit, transforming the rules of Web development. It’s not that Ruby on Rails contained revolutionary technology but that the concept took existing ingredients and blended them in such a compelling and appealing way as to put existing platforms to shame. Ruby on Rails (or just Rails, as it is commonly called) embraced an MVC architecture (which we describe shortly). By applying MVC and working in tune with the HTTP protocol instead of against it, by promoting conventions instead of the need for configuration, and by integrating an object-relational mapping (ORM) tool into its core, Rails applications more or less fell into place without much effort. It was as if this was how Web development should have been all along; as if we had suddenly realized we had been fighting our tools all these years and now the war was over. Rails shows that Web standards compliance and RESTfulness don’t need to be hard. It also shows that agile development and TDD work best when the framework is designed to support them. The rest of the Web development world has been catching up ever since. 7
Description: