Programming Microsoft ASP.NET MVC

Book description

Develop next-generation web applications with ASP.NET MVC

Go deep into the architecture and features of ASP.NET MVC 5, and learn how to build web applications that work well on both the desktop and mobile devices. Web development expert Dino Esposito takes you through the web framework’s Model-View-Controller (MVC) design model, and covers the tools you need to cleanly separate business logic from the user interface. If you’re an experienced web developer new to ASP.NET MVC, this practical guide will get you going.

Discover how to:

  • Build web applications that are easy to test and maintain

  • Dive into the functions of controllers—the heart of an MVC site

  • Explore the structure and behavior of a view engine

  • Process a variety of input data using a custom model binder

  • Automate the writing of input forms, and streamline validation

  • Design websites for mobile devices, localization, and error handling

  • Provide security by implementing a membership system

  • Inject script code into your site using JavaScript and jQuery

  • Use Responsive Web Design to make sites mobile-friendly

  • Table of contents

    1. Dedication
    2. Introduction
      1. Who should read this book
        1. Assumptions
      2. Who should not read this book
      3. Organization of this book
      4. System requirements
      5. Code samples
        1. Installing the code samples
        2. Using the code samples
      6. Errata & book support
      7. We want to hear from you
      8. Stay in touch
    3. I. ASP.NET MVC fundamentals
      1. 1. ASP.NET MVC controllers
        1. Routing incoming requests
          1. Simulating the ASP.NET MVC runtime
            1. Defining the syntax of recognized URLs
            2. Defining the behavior of the HTTP handler
            3. Invoking the HTTP handler
          2. The URL routing HTTP module
            1. Superseding URL rewriting
            2. Routing the requests
            3. The internal structure of the URL routing module
          3. Application routes
            1. URL patterns and routes
            2. Defining application routes
            3. Processing routes
            4. Route handler
            5. Handling requests for physical files
            6. Preventing routing for defined URLs
            7. Attribute routing
        2. The controller class
          1. Aspects of a controller
            1. Granularity of controllers
            2. Stateless components
            3. Further layering is up to you
            4. Highly testable
          2. Writing controller classes
            1. From routing to controllers
            2. From routing to actions
            3. Actions and HTTP verbs
            4. Action methods
          3. Processing input data
            1. Getting input data from the Request object
            2. Getting input data from the route
            3. Getting input data from multiple sources
            4. The ValueProvider dictionary
          4. Producing action results
            1. Inside the ActionResult class
            2. Predefined action result types
            3. The mechanics of executing action results
            4. Returning HTML markup
            5. Returning JSON content
        3. Summary
      2. 2. ASP.NET MVC views
        1. The structure and behavior of a view engine
          1. The mechanics of a view engine
            1. Detecting registered view engines
            2. Anatomy of a view engine
            3. Who calls the view engine?
            4. The view object
          2. Definition of the view template
            1. Resolving the template
            2. Default conventions and folders
            3. The template for the view
            4. The master view
        2. HTML helpers
          1. Basic helpers
            1. Rendering HTML forms
            2. Rendering input elements
            3. Action links
            4. Partial views
            5. The HtmlHelper class
          2. Templated helpers
            1. Flavors of a templated helper
            2. The Display helpers
            3. The Editor helpers
          3. Custom helpers
            1. The structure of an HTML helper
            2. MvcHtmlString is better than just a string
            3. A sample HTML helper
            4. A sample Ajax helper
        3. The Razor view engine
          1. Inside the view engine
            1. Search locations
            2. Code nuggets
            3. Special expressions of code nuggets
            4. Conditional nuggets
            5. The Razor view object
          2. Designing a sample view
            1. Defining the model for the view
            2. Defining a master view
            3. Defining sections
            4. Default content for sections
            5. Nested layouts
            6. Declarative HTML helpers
        4. Coding the view
          1. Modeling the view
            1. The ViewData dictionary
            2. The ViewBag dictionary
            3. Strongly typed view models
            4. Packaging the view-model classes
          2. Advanced features
            1. Custom view engines
            2. Render actions
            3. Child actions
        5. Summary
      3. 3. The model-binding architecture
        1. The input model
          1. Evolving from the Web Forms input processing
            1. Role of server controls
            2. Role of the view state
          2. Input processing in ASP.NET MVC
            1. The role of model binders
            2. Flavors of a model
        2. Model binding
          1. Model-binding infrastructure
            1. Analyzing the method’s signature
            2. Getting the binder for the type
          2. The default model binder
            1. Binding primitive types
            2. Dealing with optional values
            3. Value providers and precedence
            4. Binding complex types
            5. Binding collections
            6. Binding collections of complex types
            7. Binding content from uploaded files
          3. Customizable aspects of the default binder
            1. The Bind attribute
            2. Creating whitelists of properties
            3. Creating blacklists of properties
            4. Aliasing parameters by using a prefix
        3. Advanced model binding
          1. Custom type binders
            1. Customizing the default binder
            2. Implementing a model binder from scratch
            3. Registering a custom binder
          2. A sample DateTime model binder
            1. The displayed data
            2. The controller methods
            3. Creating the DateTime binder
        4. Summary
      4. 4. Input forms
        1. General patterns of data entry
          1. A classic Select-Edit-Post scenario
            1. Presenting data and handling the selection
            2. Editing data
            3. Saving data
          2. Applying the Post-Redirect-Get pattern
            1. Keeping the URL and content synchronized
            2. Splitting POST and GET actions
            3. Updating only via POST
            4. Saving temporary data across redirects
        2. Automating the writing of input forms
          1. Predefined display and editor templates
            1. Annotating data members for display
            2. Default templates for data types
            3. Custom templates for data types
            4. Read-only members
          2. Custom templates for model data types
            1. Tabular templates
            2. Dealing with nested models
        3. Input validation
          1. Using data annotations
            1. Validation provider infrastructure
            2. Decorating a model class
            3. Dealing with enumerated types
            4. Controlling error messages
          2. Advanced data annotations
            1. Cross-property validation
            2. Creating custom validation attributes
            3. Enabling client-side validation
            4. Culture-based, client-side validation
            5. Validating properties remotely
          3. Self-validation
            1. The IValidatableObject interface
            2. Benefits of centralized validation
            3. The IClientValidatable interface
            4. Dynamic server-side validation
        4. Summary
    4. II. ASP.NET MVC software design
      1. 5. Aspects of ASP.NET MVC applications
        1. ASP.NET intrinsic objects
          1. HTTP response and SEO
            1. Permanent redirection
            2. Devising routes and URLs
            3. The trailing slash
          2. Managing the session state
            1. Using the Session object
            2. Never outside the controller
          3. Caching data
            1. The bright side and dark side of the native Cache object
            2. Injecting a caching service
            3. A better way of injecting a caching service
            4. Distributed caching
            5. Caching the method response
            6. Partial output caching
        2. Error handling
          1. Handling program exceptions
            1. Handling exceptions directly
            2. Overriding the OnException method
            3. Using the HandleError attribute
          2. Global error handling
            1. Global error handling from global.asax
            2. Global error handling using an HTTP module
            3. Intercepting model-binding exceptions
            4. Handling route exceptions
          3. Dealing with missing content
            1. Catch-all route
            2. Skipping IIS error-handling policies
        3. Localization
          1. Using localizable resources
            1. Localizable text
            2. Localizable files
            3. Referencing embedded files
            4. Localizable views
          2. Dealing with localizable applications
            1. Auto-adapting applications
            2. Multilingual applications
            3. Changing culture programmatically
            4. Getting localized data from a service
        4. Summary
      2. 6. Securing your application
        1. Security in ASP.NET MVC
          1. Authentication and authorization
            1. Configuring authentication in ASP.NET MVC
            2. Restricting access to action methods
            3. Allowing anonymous callers
            4. Handling authorization for action methods
            5. Authorization and output caching
            6. Hiding critical user interface elements
          2. Separating authentication from authorization
            1. Anonymous or not authorized?
            2. Authentication filters
        2. Implementing a membership system
          1. Defining a membership controller
            1. Validating user credentials
            2. Integrating with the membership API
            3. Using the SimpleMembership API
            4. Integrating with the role API
            5. ASP.NET identity
            6. Authenticating users by using ASP.NET Identity
          2. The Remember-Me feature and Ajax
            1. Reproducing the problem
            2. Solving the problem
        3. External authentication services
          1. The OpenID protocol
            1. Identifying users through an OpenID provider
            2. OpenID vs. OAuth
          2. Authenticating via social networks
            1. Registering your application with Twitter
            2. Enabling social authentication in ASP.NET MVC
            3. Starting the authentication process
            4. Dealing with the Twitter response
            5. From authentication to membership
            6. Beyond authentication
        4. Summary
      3. 7. Design considerations for ASP.NET MVC controllers
        1. Shaping up your controller
          1. Choosing the right stereotype
            1. RDD at a glance
            2. Breaking down the execution of a request
            3. Acting as a “Controller”
            4. Acting as a “Coordinator”
          2. Fat-free controllers
            1. Short is always better
            2. Action methods coded as view-model builders
            3. Worker services
            4. Implementing a worker service
            5. Do we really need controllers?
            6. The ideal action method code
        2. Connecting the presentation and back end
          1. The Layered Architecture pattern
            1. Beyond classic layers
            2. The (idiomatic) presentation layer
            3. The application layer
            4. The domain layer
            5. Exposing entities of the domain
            6. The infrastructure layer
          2. Injecting data and services in layers
            1. The Dependency Inversion Principle
            2. The Service Locator pattern
            3. The Dependency Injection pattern
            4. Using tools for Inversion of Control
            5. The poor-man’s DI
          3. Gaining control of the controller factory
            1. Registering a custom controller factory
            2. Building a custom controller factory
            3. A Unity-based controller factory
        3. Summary
      4. 8. Customizing ASP.NET MVC controllers
        1. The extensibility model of ASP.NET MVC
          1. The provider-based model
            1. Gallery of extensibility points
            2. A realistic scenario: alternate TempData storage
            3. Using custom components in your applications
          2. The Service Locator pattern
            1. Service Locator vs. Dependency Injection
            2. SL in ASP.NET MVC
            3. Defining your dependency resolver
        2. Adding aspects to controllers
          1. Action filters
            1. Embedded and external filters
            2. Classification of action filters
            3. Built-in action filters
            4. Global filters
          2. Gallery of action filters
            1. Adding a response header
            2. Compressing the response
            3. View Selector
          3. Special filters
            1. Action name selectors
            2. Action method selectors
            3. Restricting a method to Ajax calls only
            4. Restricting a method to a given submit button
          4. Building a dynamic loader filter
            1. Interception points for filters
            2. Adding an action filter by using fluent code
            3. Customizing the action invoker
            4. Registering the custom invoker
            5. Enabling dynamic loading via a filter provider
        3. Action result types
          1. Built-in action result types
            1. Returning a custom status code
            2. Returning JavaScript code
            3. Returning JavaScript Object Notation data
            4. Returning primitive types
          2. Custom result types
            1. Returning JSONP Strings
            2. Returning syndication feed
            3. Dealing with binary content
            4. Returning PDF files
        4. Summary
      5. 9. Testing and testability in ASP.NET MVC
        1. Testability and design
          1. DfT
            1. The attribute of control
            2. The attribute of visibility
            3. The attribute of simplicity
          2. Loosen up your design
            1. Interface-based programming
            2. Relativity of software testability
            3. Testability and coupling
            4. Testability and object orientation
        2. The basics of unit testing
          1. Working with a test harness
            1. Choosing a test environment
            2. Test fixtures
            3. Arrange, act, assert
            4. Data-driven tests
          2. Aspects of testing
            1. Very limited scope
            2. Testing in isolation
            3. Fakes and mocks
            4. Number of assertions per test
            5. Testing inner members
            6. Code coverage
        3. Testing your ASP.NET MVC code
          1. Which part of your code should you test?
            1. How do I find relevant code to test?
            2. The domain layer
            3. The orchestration layer
            4. The data access layer
          2. Unit testing ASP.NET MVC code
            1. Testing whether the returned view is correct
            2. Testing localization
            3. Testing redirections
            4. Testing routes
          3. Dealing with dependencies
            1. About mock and fake objects
            2. Testing code that performs data access
          4. Mocking the HTTP context
            1. Mocking the HttpContext object
            2. Mocking the Request object
            3. Mocking the Response object
            4. Mocking the Session object
            5. Mocking the Cache object
        4. Summary
      6. 10. An executive guide to Web API
        1. The whys and wherefores of Web API
          1. The need for a unified HTTP API
            1. Beyond WCF
            2. What Web API means for client applications
            3. What Web API means for ASP.NET Web Forms applications
          2. MVC controllers vs. Web API
            1. The Controller class does it all
            2. Feeling the difference
            3. Building RESTful applications
        2. Putting Web API to work
          1. Designing a RESTful interface
            1. Defining the resource type
            2. The ApiController Class
            3. Routing to action methods
            4. Dealing with multiple matches
            5. Active naming conventions
          2. Expected method behavior
            1. Semantic of POST methods
            2. Semantic of PUT methods
            3. Semantic of DELETE methods
            4. Semantic of other methods
          3. Using the Web API
            1. Invoking Web API from JavaScript
            2. Invoking from server-side code
            3. Making the call asynchronous
          4. Designing an RPC-oriented Interface
            1. CRUD-over-HTTP is just one option
            2. Action attributes
            3. Custom routes
            4. Attribute routing
            5. Turning on attribute routing
          5. Security considerations
            1. The host takes care of security
            2. Using Basic authentication
            3. Using access tokens
            4. Using OAuth
            5. Using cross-origin resource sharing
        3. Negotiating the response format
          1. The ASP.NET MVC approach
            1. Understanding the requested format
            2. Enforcing data and format separation
          2. How content negotiation works in Web API
            1. Involved HTTP headers
            2. Changing default formatters
            3. Defining formatters for specific types
        4. Summary
    5. III. Mobile clients
      1. 11. Effective JavaScript
        1. Revisiting the JavaScript language
          1. Language basics
            1. The type system
            2. Null vs. undefined
            3. Local and global variables
            4. Variables and hoisting
            5. Objects
            6. Functions
          2. Object-orientation in JavaScript
            1. Making objects look like classes
            2. Using closures
            3. Using prototypes
            4. Plain custom objects vs. a hierarchy of classes
        2. jQuery’s executive summary
          1. DOM queries and wrapped sets
            1. The root object
            2. Running a query
            3. Enumerating the content of a wrapped set
          2. Selectors
            1. Basic selectors
            2. Compound selectors
            3. Predefined filters
            4. Filter vs. find
            5. Chaining operations on a wrapped set
          3. Events
            1. Binding and unbinding
            2. Live event binding
            3. Page and DOM readiness
        3. Aspects of JavaScript programming
          1. Unobtrusive code
            1. Style the view by using code
            2. Pragmatic rules of unobtrusive JavaScript
          2. Reusable packages and dependencies
            1. The Namespace pattern
            2. The Module pattern
          3. Script and resource loading
            1. The download is always synchronous
            2. Scripts at the bottom
            3. Dealing with static files
            4. Using sprites
          4. Bundling and minification
            1. Bundling related resources
            2. Bundling script files
            3. Adding minification
        4. Summary
      2. 12. Making websites mobile-friendly
        1. Technologies for enabling mobile on sites
          1. HTML5 for the busy developer
            1. Semantic markup
            2. What’s different in HTML5?
            3. A native collapsible element
            4. New input types
            5. The <datalist> element
            6. Local storage
            7. Audio and video
          2. RWD
            1. Feature detection
            2. CSS media queries
            3. CSS media queries in action
            4. Fluid layout
            5. When RWD meets mobile
          3. jQuery Mobile’s executive summary
            1. Themes and styles
            2. Data-* attributes
            3. Pages in jQM
            4. Header and footer
            5. Lists, lists, and lists
            6. Fluid layout
            7. Collapsible panels
          4. Twitter Bootstrap at a glance
            1. Setting up Bootstrap
            2. The grid system
            3. Navigation bars
            4. Embellishing the UI with icons and images
            5. Drop-down menus
            6. Button groups
        2. Adding mobile capabilities to an existing site
          1. Routing users to the correct site
            1. The routing algorithm
            2. Implementing the routing algorithm
            3. Tracking the chosen route
            4. Tweaking the configuration files
          2. From mobile to devices
        3. Summary
      3. 13. Building sites for multiple devices
        1. Understanding display modes in ASP.NET MVC
          1. Separated mobile and desktop views
            1. Built-in support for mobile views
            2. Default configuration for mobile views
          2. Rules for selecting the display mode
            1. Naming a display mode
            2. The matching rule
          3. Adding custom display modes
            1. Listing current display modes
            2. Going beyond the default configuration
            3. Defining custom display modes
        2. Introducing the WURFL database
          1. Structure of the repository
            1. The overall XML schema
            2. Groups of capabilities
            3. WURFL patch files
          2. Essential WURFL capabilities
            1. Identifying the current device
            2. Serving browser-specific content
        3. Using WURFL with ASP.NET MVC display modes
          1. Configuring the WURFL framework
            1. Installing the NuGet package
            2. Referencing the device database
            3. Initializing the WURFL runtime
          2. Detecting device capabilities
            1. Processing the HTTP request
            2. Virtual capabilities
            3. Accuracy vs. performance
          3. Using WURFL-based display modes
            1. Selecting display modes
            2. Defining matching rules
            3. A multidevice site in action
          4. The WURFL cloud API
            1. Setting up the API
            2. Cloud API vs. on-premises API
        4. Why you should consider server-side solutions
        5. Summary
    6. A. About the author
    7. Index
    8. About the Author
    9. Copyright

    Product information

    • Title: Programming Microsoft ASP.NET MVC
    • Author(s):
    • Release date: February 2014
    • Publisher(s): Microsoft Press
    • ISBN: 9780735681095