Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống
1
/ 738 trang
THÔNG TIN TÀI LIỆU
Thông tin cơ bản
Định dạng
Số trang
738
Dung lượng
23,64 MB
Nội dung
Freeman
US $54.99
Shelve in
.NET
User level:
Intermediate–Advanced
www.apress.com
SOURCE CODE ONLINE
RELATED
Pro ASP.NET MVC 4
The ASP.NET MVC4 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 MVC4 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 MVC4 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.
BOOKS FOR PROFESSIONALS BY PROFESSIONALS
®
THE EXPERT’S VOICE
®
IN .NET
FOURTH
EDITION
www.it-ebooks.info
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.
www.it-ebooks.info
v
Contents at a Glance
■ Contents vii
■ About the Author xxi
■ About the Technical Reviewer xxii
■ Acknowledgments xxiii
■Part 1: Introducing ASP.NET MVC4 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 MVC4 in Detail 301
■ Chapter 12: Overview of MVC Projects 303
■ Chapter 13: URL Routing 323
www.it-ebooks.info
■ CONTENTS AT A GLANCE
vi
■ 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
www.it-ebooks.info
P A R T 1
Introducing ASP.NET MVC4
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.
www.it-ebooks.info
CHAPTER 1
3
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 MVC4.
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
(CGI)
*
Simple
Flexible
Only option at the time
Runs outside the Web
server, so is resource-
intensive (spawns a
separate operating
system process per
request)
Low-level
Bronze age Microsoft Internet Database
Connector (IDC)
Runs inside Web server Just a wrapper for SQL
queries and templates
for formatting result
sets
1996 Active Server Pages (ASP) General purpose Interpreted at runtime
Encourages “spaghetti
code”
www.it-ebooks.info
CHAPTER 1 WHAT’S THE BIG IDEA?
4
Period Technology Strengths Weaknesses
2002/03 ASP.NET Web Forms 1.0/1.1 Compiled
“Stateful” UI
Vast infrastructure
Encourages object-
oriented programming
Heavy on bandwidth
Ugly HTML
Untestable
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 MVC4.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
www.it-ebooks.info
CHAPTER 1 WHAT’S THE BIG IDEA?
5
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.
www.it-ebooks.info
CHAPTER 1 WHAT’S THE BIG IDEA?
6
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.
www.it-ebooks.info
CHAPTER 1 WHAT’S THE BIG IDEA?
7
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.
www.it-ebooks.info
[...]... 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 about the theory and practice of this architecture in Chapter 3 By embracing and adapting the MVC pattern, the ASP. NET MVC Framework provides... It is probably the most popular NET Web application platform created outside Redmond, and it did achieve reasonably widespread adoption in its day However, since the launch of ASP. NET MVC, the MonoRail project is rarely heard of The momentum of enthusiasm and innovation in the NET Web development world is now focused on ASP. NET MVC What’s New in ASP. NET MVC 4? Version 4 of the MVC Framework provides... www.it-ebooks.info CHAPTER 2 YOUR FIRST MVC APPLICATION Creating a New ASP. NET MVC Project We are going to start by creating a new MVC project in Visual Studio Select New Project from the File menu to open the New Project dialog If you select the Web templates in the Visual C# section, you will see that one of the available project types is ASP. NET MVC4 Web Application Select this project type, as shown in Figure... your own custom controls from earlier ASP. NET projects, in an ASP. NET MVC application (as long as they don’t depend on Web Forms–specific notions, such as View State) Modern API Since its inception in 2002, Microsoft’s NET platform has evolved relentlessly, supporting and even defining the state-of-the-art aspects of modern programming ASP. NET MVC4 is built for NET 4. 5, so its API can take full advantage... tightly integrated into ASP. NET MVC as the equivalents are into Rails Comparisons with MonoRail MonoRail is an earlier NET-based MVC Web application platform, created as part of the open source Castle project and in development since 2003 In many ways, MonoRail acted as the prototype for ASP. NET MVC MonoRail demonstrated how a Rails-like MVC architecture could be built on top of ASP. NET and established... ASP. NET MVC meshes so well with the popular jQuery library that Microsoft ships jQuery as a built-in part of the default ASP. NET MVC project template, and even lets you directly reference the jQuery js file on Microsoft’s own content delivery network (CDN) servers ASP. NET MVC generated pages don’t contain any View State data, so they can be hundreds of kilobytes smaller than typical pages from ASP. NET... 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 we describe in Chapter 17) This is a way to handle HTTP requests with nonblocking I/O and scale up to handle more requests per CPU And as you will learn, ASP. NET MVC integrates very well with... Chapters 13 and 14 Built on the Best Parts of the ASP. NET Platform Microsoft’s existing ASP. NET platform provides a mature, well-proven set of components and facilities for developing effective and efficient Web applications First and most obviously, as ASP. NET MVC is based on the NET platform, you have the flexibility to write code in any NET language and access the same API features—not just in MVC itself... different types of MVC project templates 16 www.it-ebooks.info CHAPTER 2 YOUR FIRST MVC APPLICATION Figure 2-2 Selecting a type of MVC 4 project The different MVC project templates create projects with varying amounts of basic support for features such as authentication, navigation and visual styles For this chapter, we are going to keep things simple Select the Empty option, which creates a project with... download the MVC source code from http://aspnetwebstack.codeplex.com Who Should Use ASP. NET MVC? As with any new technology, the fact of ASP. NET MVC s existence isn’t a compelling reason to adopt it Here, we will give you our view of how the MVC Framework compares with the most obvious alternatives We have tried to be as unbiased as two people writing a book about the MVC Framework can be, but we know that . object- oriented programming Heavy on bandwidth Ugly HTML Untestable 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. 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. Freeman US $ 54. 99 Shelve in .NET User level: Intermediate–Advanced www.apress.com SOURCE CODE ONLINE RELATED Pro ASP. NET MVC 4 The ASP. NET MVC 4 Framework is the latest evolution of Microsoft’s ASP. NET