Programming ASP.NET MVC 4

Book description

Get up and running with ASP.NET MVC 4, and learn how to build modern server-side web applications. This guide helps you understand how the framework performs, and shows you how to use various features to solve many real-world development scenarios you’re likely to face. In the process, you’ll learn how to work with HTML, JavaScript, the Entity Framework, and other web technologies.

You’ll start by learning core concepts such as the Model-View-Controller architectural pattern, and then work your way toward advanced topics. The authors demonstrate ASP.NET MVC 4 best practices and techniques by building a sample online auction site ("EBuy") throughout the book.

  • Learn the similarities between ASP.NET MVC 4 and Web Forms
  • Use Entity Framework to create and maintain an application database
  • Create rich web applications, using jQuery for client-side development
  • Incorporate AJAX techniques into your web applications
  • Learn how to create and expose ASP.NET Web API services
  • Deliver a rich and consistent experience for mobile devices
  • Apply techniques for error handling, automated testing, and build automation
  • Use various options to deploy your ASP.NET MVC 4 application

Publisher resources

View/Submit Errata

Table of contents

  1. Programming ASP.NET MVC 4
  2. SPECIAL OFFER: Upgrade this ebook with O’Reilly
  3. Preface
    1. Audience
    2. Assumptions This Book Makes
    3. Conventions Used in This Book
    4. Using Code Examples
    5. Safari® Books Online
    6. How to Contact Us
  4. I. Up and Running
    1. 1. Fundamentals of ASP.NET MVC
      1. Microsoft’s Web Development Platforms
        1. Active Server Pages (ASP)
        2. ASP.NET Web Forms
        3. ASP.NET MVC
      2. The Model-View-Controller Architecture
        1. The Model
        2. The View
        3. The Controller
      3. What’s New in ASP.NET MVC 4?
      4. Introduction to EBuy
      5. Installing ASP.NET MVC
      6. Creating an ASP.NET MVC Application
        1. Project Templates
        2. Convention over Configuration
        3. Running the Application
      7. Routing
        1. Configuring Routes
      8. Controllers
        1. Controller Actions
        2. Action Results
        3. Action Parameters
          1. Model binding basics
          2. Model binding complex objects
        4. Action Filters
      9. Views
        1. Locating Views
        2. Hello, Razor!
        3. Differentiating Code and Markup
          1. Code nuggets
          2. Code blocks
        4. Layouts
        5. Partial Views
        6. Displaying Data
          1. Cleaner access to ViewData values via ViewBag
          2. View models
          3. Strongly typed views
        7. HTML and URL Helpers
      10. Models
      11. Putting It All Together
        1. The Route
        2. The Controller
          1. Controller templates
        3. The View
      12. Authentication
        1. The AccountController
      13. Summary
    2. 2. ASP.NET MVC for Web Forms Developers
      1. It’s All Just ASP.NET
        1. Tools, Languages, and APIs
        2. HTTP Handlers and Modules
        3. Managing State
        4. Deployment and Runtime
      2. More Differences than Similarities
        1. Separation of Application Logic and View Logic
        2. URLs and Routing
        3. State Management
        4. Rendering HTML
          1. HTML helpers versus server controls
          2. Partial views versus user controls
          3. Layouts versus master pages
      3. Authoring ASP.NET MVC Views Using Web Forms Syntax
        1. A Word of Caution
      4. Summary
    3. 3. Working with Data
      1. Building a Form
      2. Handling Form Posts
      3. Saving Data to a Database
        1. Entity Framework Code First: Convention over Configuration
        2. Creating a Data Access Layer with Entity Framework Code First
      4. Validating Data
        1. Specifying Business Rules with Data Annotations
          1. Required fields
          2. Valid ranges
          3. Custom error messages
        2. Displaying Validation Errors
      5. Summary
    4. 4. Client-Side Development
      1. Working with JavaScript
      2. Selectors
      3. Responding to Events
      4. DOM Manipulation
      5. AJAX
      6. Client-Side Validation
      7. Summary
  5. II. Going to the Next Level
    1. 5. Web Application Architecture
      1. The Model-View-Controller Pattern
        1. Separation of Concerns
        2. MVC and Web Frameworks
      2. Architecting a Web Application
        1. Logical Design
        2. ASP.NET MVC Web Application Logical Design
        3. Logical Design Best Practices
        4. Physical Design
        5. Project Namespace and Assembly Names
        6. Deployment Options
        7. Physical Design Best Practices
          1. Performance and scalability
          2. Bandwidth and latency
      3. Design Principles
        1. SOLID
          1. The Single Responsibility Principle
          2. The Open/Closed Principle
          3. The Liskov Substitution Principle
          4. The Interface Segregation Principle
          5. The Dependency Inversion Principle
        2. Inversion of Control
          1. Understanding dependencies
          2. Service location
          3. Dependency injection
          4. Picking an IoC container
          5. Using Inversion of Control to extend ASP.NET MVC
      4. Don’t Repeat Yourself
      5. Summary
    2. 6. Enhancing Your Site with AJAX
      1. Partial Rendering
        1. Rendering Partial Views
          1. Rendering a “normal” view
          2. Rendering a partial view
          3. Managing complexity with partial views
      2. JavaScript Rendering
        1. Rendering JSON Data
          1. Avoiding JSON hijacking with JsonRequestBehavior
        2. Requesting JSON Data
        3. Client-Side Templates
      3. Reusing Logic Across AJAX and Non-AJAX Requests
        1. Responding to AJAX Requests
        2. Responding to JSON Requests
        3. Applying the Same Logic Across Multiple Controller Actions
      4. Sending Data to the Server
        1. Posting Complex JSON Objects
        2. Model Binder Selection
          1. Replacing the default (fallback) binder
          2. Adorning models with custom attributes
          3. Registering a global binder
        3. Sending and Receiving JSON Data Effectively
      5. Cross-Domain AJAX
        1. JSONP
          1. Making a JSONP request
          2. Adding JSONP support to ASP.NET MVC controller actions
        2. Enabling Cross-Origin Resource Sharing
      6. Summary
    3. 7. The ASP.NET Web API
      1. Building a Data Service
        1. Registering Web API Routes
        2. Leaning on Convention over Configuration
        3. Overriding Conventions
        4. Hooking Up the API
      2. Paging and Querying Data
      3. Exception Handling
      4. Media Formatters
      5. Summary
    4. 8. Advanced Data
      1. Data Access Patterns
        1. Plain Old CLR Objects
        2. Using the Repository Pattern
        3. Object Relational Mappers
      2. Entity Framework Overview
        1. Choosing a Data Access Approach
        2. Database Concurrency
      3. Building a Data Access Layer
        1. Using Entity Framework Code First
          1. Code First data annotations
          2. Overriding conventions
        2. The EBuy Business Domain Model
        3. Working with a Data Context
      4. Sorting, Filtering, and Paging Data
      5. Summary
    5. 9. Security
      1. Building Secure Web Applications
        1. Defense in Depth
        2. Never Trust Input
        3. Enforce the Principle of Least Privilege
        4. Assume External Systems Are Insecure
        5. Reduce Surface Area
        6. Disable Unnecessary Features
      2. Securing an Application
        1. Securing an Intranet Application
          1. Setting up Windows Authentication
          2. Configuring IIS Express
          3. Configuring IIS 7
          4. Using the AuthorizeAttribute
        2. Forms Authentication
          1. AccountController
          2. Authenticating users
          3. Registering new users
          4. Changing passwords
          5. Interacting via AJAX
          6. User authorization
      3. Guarding Against Attacks
        1. SQL Injection
        2. Cross-Site Scripting
        3. Cross-Site Request Forgery
          1. Using ASP.NET MVC to avoid Cross-Site Request Forgery
      4. Summary
    6. 10. Mobile Web Development
      1. ASP.NET MVC 4 Mobile Features
      2. Making Your Application Mobile Friendly
        1. Creating the Auctions Mobile View
        2. Getting Started with jQuery Mobile
        3. Enhancing the View with jQuery Mobile
          1. Improving the auctions list with jQuery Mobile’s “listview”
          2. Making the auctions list searchable with jQuery Mobile’s “data-filter”
          3. Switching between desktop and mobile views
        4. Avoiding Desktop Views in the Mobile Site
      3. Improving Mobile Experience
      4. Adaptive Rendering
        1. The Viewport Tag
        2. Mobile Feature Detection
        3. CSS Media Queries
        4. Browser-Specific Views
      5. Creating a New Mobile Application from Scratch
        1. The jQuery Mobile Paradigm Shift
        2. The ASP.NET MVC 4 Mobile Template
        3. Using the ASP.NET MVC 4 Mobile Application Template
      6. Summary
  6. III. Going Above and Beyond
    1. 11. Parallel, Asynchronous, and Real-Time Data Operations
      1. Asynchronous Controllers
        1. Creating an Asynchronous Controller
        2. Choosing When to Use Asynchronous Controllers
      2. Real-Time Asynchronous Communication
        1. Comparing Application Models
        2. HTTP Polling
          1. Browser support
          2. Downsides
        3. HTTP Long Polling
          1. Browser support
          2. Downsides
        4. Server-Sent Events
          1. Browser support
          2. Downsides
        5. WebSockets
          1. Browser support
          2. Downsides
        6. Empowering Real-Time Communication
          1. Persistent connections
          2. Hubs
        7. Configuring and Tuning
          1. Managing SignalR connections
          2. Configuring the environment
      3. Summary
    2. 12. Caching
      1. Types of Caching
        1. Server-Side Caching
        2. Client-Side Caching
      2. Server-Side Caching Techniques
        1. Request-Scoped Caching
        2. User-Scoped Caching
          1. Session lifetime
          2. Storing session data
        3. Application-Scoped Caching
        4. The ASP.NET Cache
          1. Expiration
          2. Cache dependencies
          3. Scavenging
        5. The Output Cache
          1. Configuring the cache location
          2. Varying the output cache based on request parameters
          3. Output cache profiles
        6. Donut Caching
        7. Donut Hole Caching
        8. Distributed Caching
          1. Distributed caching solutions
            1. Installing Velocity
            2. Administering your memory cluster from PowerShell
            3. Using the cache
      3. Client-Side Caching Techniques
        1. Understanding the Browser Cache
        2. App Cache
          1. Define the manifest
          2. Reference the manifest
          3. Serve the manifest correctly
        3. Local Storage
      4. Summary
    3. 13. Client-Side Optimization Techniques
      1. Anatomy of a Page
        1. Anatomy of an HttpRequest
      2. Best Practices
        1. Make Fewer HTTP Requests
        2. Use a Content Delivery Network
        3. Add an Expires or a Cache-Control Header
          1. Set up client caching in IIS
          2. Set up client caching through ASP.NET MVC
          3. Cache busting
        4. GZip Components
        5. Put Stylesheets at the Top
        6. Put Scripts at the Bottom
          1. Defer script execution
          2. Lazy loading scripts
        7. Make Scripts and Styles External
        8. Reduce DNS Lookups
        9. Minify JavaScript and CSS
        10. Avoid Redirects
        11. Remove Duplicate Scripts
        12. Configure ETags
      3. Measuring Client-Side Performance
      4. Putting ASP.NET MVC to Work
        1. Bundling and Minification
          1. Defining bundles
          2. Enabling bundles
          3. Cache busting
      5. Summary
    4. 14. Advanced Routing
      1. Wayfinding
      2. URLs and SEO
      3. Building Routes
        1. Default and Optional Route Parameters
        2. Routing Order and Priority
        3. Routing to Existing Files
        4. Ignoring Routes
        5. Catch-All Routes
      4. Route Constraints
        1. Peering into Routes Using Glimpse
      5. Attribute-Based Routing
      6. Extending Routing
        1. The Routing Pipeline
      7. Summary
    5. 15. Reusable UI Components
      1. What ASP.NET MVC Offers out of the Box
        1. Partial Views
        2. HtmlHelper Extensions or Custom HtmlHelpers
        3. Display and Editor Templates
        4. Html.RenderAction()
      2. Taking It a Step Further
        1. The Razor Single File Generator
          1. Installing the Razor Single File Generator
        2. Creating Reusable ASP.NET MVC Views
          1. Including Precompiled views in an ASP.NET MVC web application
        3. Creating Reusable ASP.NET MVC Helpers
      3. Unit Testing Razor Views
      4. Summary
  7. IV. Quality Control
    1. 16. Logging
      1. Error Handling in ASP.NET MVC
        1. Enabling Custom Errors
        2. Handling Errors in Controller Actions
        3. Defining Global Error Handlers
          1. Customizing the error page
      2. Logging and Tracing
        1. Logging Errors
          1. Simple try/catch handler
          2. Overriding Controller.OnException()
          3. Custom error filters
        2. ASP.NET Health Monitoring
      3. Summary
    2. 17. Automated Testing
      1. The Semantics of Testing
        1. Manual Testing
          1. Humans are error prone
          2. Computers are more efficient
          3. Manual testing takes time
        2. Automated Testing
      2. Levels of Automated Testing
        1. Unit Tests
          1. Atomic
          2. Repeatable
          3. Isolated/Independent
        2. Fast
        3. Integration Tests
        4. Acceptance Tests
          1. User acceptance testing
      3. What Is an Automated Test Project?
        1. Creating a Visual Studio Test Project
        2. Creating and Executing a Unit Test
      4. Testing an ASP.NET MVC Application
        1. Testing the Model
          1. Focus on the positive
          2. Protect against the negative
        2. Test-Driven Development
        3. Writing Clean Automated Tests
          1. Duplicate code
          2. Naming
        4. Testing Controllers
          1. Testing data access logic
        5. Refactoring to Unit Tests
        6. Mocking Dependencies
          1. Manually creating mock objects
          2. Using a mock framework
        7. Testing Views
          1. Testing application logic in the browser
      5. Code Coverage
        1. The Myth of 100% Code Coverage
      6. Developing Testable Code
      7. Summary
    3. 18. Build Automation
      1. Creating Build Scripts
        1. Visual Studio Projects Are Build Scripts!
        2. Adding a Simple Build Task
        3. Executing the Build
          1. Building in Visual Studio
          2. Building from the command line
        4. The Possibilities Are Endless!
      2. Automating the Build
        1. Types of Automated Builds
        2. Creating the Automated Build
      3. Continuous Integration
        1. Discovering Issues
        2. The Principles of Continuous Integration
          1. Maintain a single source repository
          2. Automate the build
          3. Make your build self-testing
          4. Have everyone commit to the mainline frequently
          5. Every commit should build the mainline on an integration machine
          6. Keep the build fast
          7. Test in a clone of the production environment
          8. Make it easy for anyone to get the latest executable
          9. Everyone can see what’s happening
          10. Automate deployment
      4. Summary
  8. V. Going Live
    1. 19. Deployment
      1. What Needs to Be Deployed
        1. Core Website Files
          1. “bin-deploying” ASP.NET MVC libraries
        2. Static Content
        3. What Not to Deploy
        4. Databases and Other External Dependencies
        5. What the EBuy Application Requires
      2. Deploying to Internet Information Server
        1. Prerequisites
          1. Deploying the ASP.NET MVC Framework assemblies
        2. Creating and Configuring an IIS Website
        3. Publishing from Within Visual Studio
          1. Copying files with MSBuild
          2. Executing database scripts with MSBuild
      3. Deploying to Windows Azure
        1. Creating a Windows Azure Account
        2. Creating a New Windows Azure Website
        3. Publishing a Windows Azure Website via Source Control
      4. Summary
  9. VI. Appendixes
    1. A. ASP.NET MVC and Web Forms Integration
      1. Choosing Between ASP.NET MVC and ASP.NET Web Forms
      2. Transitioning a Web Forms Site to ASP.NET MVC
        1. Adding ASP.NET MVC to an Existing Web Forms Application
        2. Copying Web Forms Functionality to an ASP.NET MVC Application
      3. Integrating Web Forms and ASP.NET MVC Functionality
        1. User Management
        2. Cache Management
        3. Many, Many More!
      4. Summary
    2. B. Leveraging NuGet as a Platform
      1. Installing the NuGet Command-Line Tool
      2. Creating NuGet Packages
        1. The NuSpec File
          1. Using the NuGet command-line tool
          2. Using the NuGet Package Explorer
        2. Generating the NuGet Package from a NuSpec File
          1. Specifying token values
          2. Setting the version
      3. The Anatomy of a NuGet Package
        1. Content
        2. Assemblies
        3. Tools
      4. Types of NuGet Packages
        1. Assembly Packages
      5. Tool Packages
        1. Meta Packages
      6. Sharing Your NuGet Packages
        1. Publishing to the Public NuGet.org Package Repository
          1. Using the NuGet.org package upload wizard
          2. Using the NuGet command-line tool
        2. Host Your Own Package Repository
          1. Using a filesystem repository
          2. Hosting a NuGet Server repository
      7. Tips, Tricks, and Pitfalls
        1. Pitfall: NuGet Does Not Solve “DLL Hell”
        2. Tip: Use Install-Package -Version to Install a Specific Package Version
        3. Tip: Use Semantic Versioning
        4. Tip: Mark “Beta” Packages with Prerelease Version Markers
        5. Pitfall: Avoid Specifying “Strict” Version Dependencies in Your NuSpec Files
        6. Tip: Use Custom Repositories to Control Package Versions
        7. Tip: Configure Your Continuous Integration Builds to Generate NuGet Packages
      8. Summary
    3. C. Best Practices
      1. Use the NuGet Package Manager to Manage Dependencies
      2. Depend on Abstractions
      3. Avoid the New Keyword
      4. Avoid Referring to HttpContext Directly (Use HttpContextBase)
      5. Avoid “Magic Strings”
      6. Prefer Models over ViewData
      7. Do Not Write HTML in “Backend” Code
      8. Do Not Perform Business Logic in Views
      9. Consolidate Commonly Used View Snippets with Helper Methods
      10. Prefer Presentation Models over Direct Usage of Business Objects
      11. Encapsulate if Statements with HTML Helpers in Views
      12. Prefer Explicit View Names
      13. Prefer Parameter Objects over Long Lists of Parameters
      14. Encapsulate Shared/Common Functionality, Logic, and Data with Action Filters or Child Actions (Html.RenderAction)
      15. Prefer Grouping Actions into Controllers Based on How They Relate to Business Concepts
      16. Avoid Grouping Actions into Controllers Based on Technical Relation
      17. Prefer Placing Action Filters at the Highest Appropriate Level
      18. Prefer Multiple Views (and/or Partial Views) over Complex If-Then-Else Logic That Shows and Hides Sections
      19. Prefer the Post-Redirect-Get Pattern When Posting Form Data
      20. Prefer Startup Tasks over Logic Placed in Application_Start (Global.asax)
      21. Prefer Authorize Attribute over Imperative Security Checks
      22. Prefer Using the Route Attribute over More Generic Global Routes
      23. Consider Using an Antiforgery Token to Avoid CSRF Attacks
      24. Consider Using the AcceptVerbs Attribute to Restrict How Actions May Be Called
      25. Consider Output Caching
      26. Consider Removing Unused View Engines
      27. Consider Custom ActionResults for Unique Scenarios
      28. Consider Asynchronous Controllers for Controller Tasks That Can Happen in Parallel
    4. D. Cross-Reference: Targeted Topics, Features, and Scenarios
  10. Index
  11. About the Authors
  12. Colophon
  13. SPECIAL OFFER: Upgrade this ebook with O’Reilly
  14. Copyright

Product information

  • Title: Programming ASP.NET MVC 4
  • Author(s): Jess Chadwick, Todd Snyder, Hrusikesh Panda
  • Release date: September 2012
  • Publisher(s): O'Reilly Media, Inc.
  • ISBN: 9781449320317