Pro ASP.NET MVC 5.9781430265290.pdf

Pro ASP.NET MVC 5.9781430265290.pdf - BOOKS FOR...

Info icon This preview shows page 1. Sign up to view the full content.

View Full Document Right Arrow Icon
This is the end of the preview. Sign up to access the rest of the document.

Unformatted text preview: BOOKS FOR PROFESSIONALS BY PROFESSIONALS ® RELATED Pro ASP.NET MVC 5 The ASP.NET MVC 5 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. Pro ASP.NET MVC 5 covers the advances in ASP.NET MVC 5, including the ability to define routes using C# attributes and the ability to override filters. The user experience of building MVC applications has also been substantially improved. The new, more tightly integrated, Visual Studio 2013 IDE has been created specifically with MVC application development in mind and this book covers the full suite of tools that will improve your development times and assist in reporting, debugging and deploying your code. This book also covers the popular Bootstrap JavaScript library, which has also now been included natively within MVC 5 providing you, the developer, with a wider range of multi-platform CSS and HTML5 options than ever before without the penalty of having to load-in third party libraries. What You’ll Learn: • Gain a solid architectural understanding of ASP.NET MVC 5 • Explore the entire ASP.NET MVC Framework as a cohesive whole • Learn what’s new in version 5 and how best to apply these new features to your own work • See how MVC 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 5 US $59.99 Shelve in .NET ISBN 978-1-4302-6529-0 55999 User level: Intermediate–Advanced SOURCE CODE ONLINE 9 781430 265290 For your convenience Apress has placed some of the front matter material after the index. Please use the Bookmarks and Contents at a Glance links to access them. 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 v ■ Contents at a Glance ■■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 vi Chapter 1 Putting ASP.NET MVC in Context 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 is a complete alternative to traditional ASP.NET Web Forms, delivering advantages for all but the most trivial of Web development projects. In this chapter, you’ll learn why Microsoft created ASP.NET MVC, how it compares to its predecessors and alternatives, and, finally, what’s new in ASP.NET MVC 5 and what’s covered in this book. Understanding the History of ASP.NET 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 1 Chapter 1 ■ Putting ASP.NET MVC in Context 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 eventdriven graphical user interface (GUI) over the Web. The idea was to make Web development feel just the same as Windows Forms development. Developers didn’t need to work with a series of independent HTTP requests and responses. They could think in terms of a stateful UI, and Microsoft could seamlessly transition the army of Windows desktop developers into the new world of web applications. What Is Wrong with ASP.NET Web Forms? Traditional ASP.NET Web Forms development was great in principle, but reality proved more complicated: • 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 Web Forms’ 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 serverside 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 versions of ASP.NET, 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 recent Web Forms releases, but it can still be tricky to get the HTML you expect. • Leaky abstraction: Web Forms tries to hide 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 Web Forms 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. Web Forms isn’t all bad and Microsoft has put a lot of effort into improving standards compliance, simplifying the development process, and even taking some features from ASP.NET MVC. Web Forms excels when you need quick results, and you can have a reasonably complex web app up and running within a day. But unless you are careful during development, you will find that the application you create is hard to test and hard to maintain. 2 Chapter 1 ■ Putting ASP.NET MVC in Context ■■Note  For complete details of ASP.NET Web Forms, see my Pro ASP.NET 4.5 in C# book, also published by Apress. I cover the complete framework and provide best-practice guidance for avoiding the most serious pitfalls. Web Development Today Outside Microsoft, Web development technology has been progressing rapidly and in several different directions since Web Forms was first released. 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 (HTML, CSS, JavaScript, and so forth) remain the great hope for enjoying a consistent browsing experience. Modern web platforms can’t afford to ignore the business case and the weight of developer enthusiasm for Web standards compliance. HTML5 has begun 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 AngularJS, 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 I touch on HTML5, jQuery, and its cousins in this book, but I don’t go into depth because these are topics in their own right. If you want more complete coverage, then Apress publishes my books on these subjects: Pro AngularJS, Pro jQuery 2.0, 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 or DELETE . Today’s Web applications don’t serve just HTML. Often, they must also serve JSON or XML data to client technologies such as AJAX and native smartphone applications. This happens naturally with REST, which eliminates the 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. Agile and Test-Driven Development It is not just Web development that has matured. 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 excessive forward planning. Enthusiasm for agile methodologies tends to go hand-in-hand with a set of development practices and tools (usually open source) that promote and assist these practices. 3 Chapter 1 ■ Putting ASP.NET MVC in Context Test-driven development (TDD), and its close relative, behavior-driven development (BDD), are two 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 tests 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. • UI automation tools let you simulate a series of user interactions against a complete running instance of your application. 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 change the HTML structures and element IDs, breaking test suites. 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. Traditional ASP.NET Web Forms is not amenable to these tools and techniques because of its monolithic design, and so Web Forms gets little respect from these projects. 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 I describe in Chapter 3. By applying MVC and working in tune with the HTTP protocol, 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. Rails showed that Web standards compliance and RESTfulness don’t need to be hard. It also showed 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. Node.js Another significant trend is the movement toward using JavaScript as a primary programming language. AJAX first showed that JavaScript is important; jQuery showed us that it could be powerful and elegant; and Google’s open source V8 JavaScript engine showed us that it could be fast. Today, JavaScript is becoming a serious server-side programming language. It serves as the data storage and querying language for several non-relational databases, including CouchDB and Mongo, and it is used as a general-purpose language in server-side platforms such as Node.js. Node.js has been around since 2009 and gained acceptance quickly. Its key innovations are as follows: 4 • Using JavaScript: Developers need to work only in a single language, from client-side code, through server-side logic, and even into data-querying logic via CouchDB or the like. • Being completely asynchronous: Node.js’s core API doesn’t expose any way of blocking a thread while waiting for input/output (I/O) or any other operation. All I/O is implemented by beginning the operation and then later receiving a callback when the I/O is completed. This means that Node.js makes extremely efficient use of system resources and may handle tens of thousands of concurrent requests per CPU. (Alternative platforms tend to be limited to about one hundred concurrent requests per CPU.) Chapter 1 ■ Putting ASP.NET MVC in Context Node.js remains a niche technology. Its biggest contribution to web app development has, rather oddly, been to provide a consistent JavaScript engine on which development tools can be written. Many emerging client-side JavaScript frameworks, such as AngularJS, have good tooling support based on the use of Node.js. Node.js adoption for deploying web apps has been slower. Most businesses building real applications in limited time frames typically need the infrastructure in full-stack frameworks such as Ruby on Rails and ASP.NET MVC. Node. js is mentioned here only to put some of ASP.NET MVC’s design into context against industry trends. For example, ASP.NET MVC includes asynchronous controllers (which I describe in Chapter 19). This is a way to handle HTTP requests with non-blocking I/O and scale up to handle more requests per CPU. Key Benefits of ASP.NET MVC In October 2007, Microsoft announced a new MVC Web development platform, built on the core ASP.NET platform, clearly designed as a direct response to the evolution of technologies such as Rails and as a reaction to the criticisms of Web Forms. The following sections describe how this new platform overcame the Web Forms limitations and brought ASP.NET back to the cutting edge. MVC Architecture It is important to distinguish between the MVC architectural pattern and the ASP.NET MVC Framework. The MVC pattern is not new—it dates back to 1978 and the Smalltalk project at Xerox PARC—but it has gained enormous popularity today as a pattern for Web applications, for the following reasons: • User interaction with an MVC application follows a natural cycle: the user takes an action, and in response the application changes its data model and delivers an updated view to the user. And then the cycle repeats. This is a convenient fit for Web applications delivered as a series of HTTP requests and responses. • Web applications necessitate combining several technologies (databases, HTML, and executable code, for example), usually split into a set of tiers or layers. The patterns that arise from these combinations map naturally onto the concepts in MVC. The ASP.NET MVC Framework implements the MVC pattern and, in doing so, provides greatly improved separation of concerns. In fact, ASP.NET MVC implements a modern variant of the MVC pattern that is especially suitable for Web applications. You will learn more abo...
View Full Document

{[ snackBarMessage ]}

What students are saying

  • Left Quote Icon

    As a current student on this bumpy collegiate pathway, I stumbled upon Course Hero, where I can find study resources for nearly all my courses, get online help from tutors 24/7, and even share my old projects, papers, and lecture notes with other students.

    Student Picture

    Kiran Temple University Fox School of Business ‘17, Course Hero Intern

  • Left Quote Icon

    I cannot even describe how much Course Hero helped me this summer. It’s truly become something I can always rely on and help me. In the end, I was not only able to survive summer classes, but I was able to thrive thanks to Course Hero.

    Student Picture

    Dana University of Pennsylvania ‘17, Course Hero Intern

  • Left Quote Icon

    The ability to access any university’s resources through Course Hero proved invaluable in my case. I was behind on Tulane coursework and actually used UCLA’s materials to help me move forward and get everything together on time.

    Student Picture

    Jill Tulane University ‘16, Course Hero Intern