List of Listings – ASP.NET MVC 2 in Action

List of Listings

Chapter 1. High-speed beginner ramp-up

Listing 1.1. Route definitions

Listing 1.2. The HomeController class

Listing 1.3. The Index.aspx view

Listing 1.4. Creating your first controller

Listing 1.5. The GuestBook Index view

Listing 1.6. An action to respond to the form post

Listing 1.7. The ThankYou.aspx view

Listing 1.8. Using the Html.BeginForm helper to generate a form tag

Listing 1.9. Creating a view model for the GuestBook application

Listing 1.10. Accepting a complex object as an action parameter

Listing 1.11. Changing the Index view to ViewPage<T>

Listing 1.12. Providing the expected model instance to the view

Listing 1.13. Using strongly typed view helpers instead of strings

Listing 1.14. Implementing Post-Redirect-Get

Listing 1.15. The ThankYou view, which uses a helper to display the model object

Chapter 2. Presentation model

Listing 2.1. The CustomerSummary class

Listing 2.2. A controller action preparing the presentation model

Listing 2.3. Defining the model in the Page directive

Listing 2.4. Using the model in the view

Listing 2.5. The input model

Listing 2.6. A view using the input model

Listing 2.7. Model binding form values to the input model

Listing 2.8. A combined display and input model

Listing 2.9. Working with the input model

Chapter 3. View fundamentals

Listing 3.1. Using the ViewResult object to render a view

Listing 3.2. The Profile class

Listing 3.3. The Show controller action

Listing 3.4. Using ViewData information to hide a link

Listing 3.5. Skeleton definition of ViewPage<T>

Listing 3.6. Passing a collection of profiles to our view

Listing 3.7. Inheriting from ViewPage<T> for a strongly typed view

Listing 3.8. Displaying a list of profiles in our view

Listing 3.9. Our LogOnModel class

Listing 3.10. Rendering the account information input form

Listing 3.11. HTML generated from expression-based HtmlHelper methods

Listing 3.12. The signature of the LogOn action using the view model as a parameter

Listing 3.13. Using EditorForModel for a simple model

Listing 3.14. The Change Password model

Listing 3.15. Using EditorFor for extra layout control

Listing 3.16. The template markup for our ChangePasswordModel template

Listing 3.17. Creating a custom Object template

Chapter 4. Controller basics

Listing 4.1. SimpleController, which populates ViewData and renders a view

Listing 4.2. An action that prepares a presentation model for a view

Listing 4.3. A value object bound to an action from a route value

Listing 4.4. A complex object bound to an action from a form post

Listing 4.5. The success path in an action

Listing 4.6. The alternate path

Listing 4.7. Testing that we redirect to the correct URL

Listing 4.8. Dependency defined in the constructor

Listing 4.9. Using Rhino Mocks to streamline code for fakes

Chapter 5. Consuming third-party components

Listing 5.1. An action that renders a list of Person objects

Listing 5.2. Using the MvcContrib Grid with more control

Listing 5.3. Adding the SlickUpload configuration sections

Listing 5.4. Turning off global SlickUpload request handling

Listing 5.5. Configuring location-specific SlickUpload information

Listing 5.6. Adding the SlickUpload HTTP handler and HTTP module

Listing 5.7. The UploadController’s Index action

Listing 5.8. The Index view using the SlickUpload web control

Listing 5.9. The UploadResult action

Listing 5.10. Displaying the file metadata

Chapter 6. Hosting ASP.NET MVC applications

Listing 6.1. Our simple controller

Listing 6.2. Route configuration with the .aspx extension

Listing 6.3. Route configuration using the custom .mvc extension

Chapter 7. Leveraging existing ASP.NET features

Listing 7.1. Binding a GridView from the view itself

Listing 7.2. Wrapping the cache in our own testable interface

Listing 7.3. Using the cache wrapper in our controllers

Listing 7.4. Testing an action that accesses the cache

Listing 7.5. Caching the result of an action for 100 seconds

Listing 7.6. An action that uses Session

Listing 7.7. Testing controllers that use Session

Listing 7.8. Enabling tracing with Web.config

Listing 7.9. Setting up the personalization properties

Listing 7.10. Passing the profile dictionary to the view

Listing 7.11. Displaying profile data on the view

Listing 7.12. Editing the profile data

Listing 7.13. Pulling strings out of the resource file based on the current culture

Listing 7.14. Enabling autoculture selection from the browser

Listing 7.15. Defining our site structure in Web.sitemap

Listing 7.16. Using the server control to display our current path in the site map

Chapter 9. Extending the controller

Listing 9.1. Using the ChildActionOnlyAttribute

Listing 9.2. The CsvActionResult class

Listing 9.3. The simplified action method that uses CsvActionResult

Listing 9.4. Moving hard-to-test code into an ActionResult

Listing 9.5. Action method that uses the LogoutActionResult

Chapter 10. Advanced view techniques

Listing 10.1. A master page defined for an MVC view

Listing 10.2. Rendering a partial from a parent view

Listing 10.3. A partial to display a row for a Profile model

Listing 10.4. Displaying a child action for a logon widget

Listing 10.5. Our logon widget child action

Listing 10.6. The Edit profile action

Listing 10.7. Current options for building route-based URLs

Listing 10.8. The ParamBuilder object

Listing 10.9. Our base view page class

Listing 10.10. Using the ParamBuilder in our view

Listing 10.11. Spark configuration code

Listing 10.12. A simple Product model

Listing 10.13. A ProductController for displaying Product objects

Listing 10.14. The entire Application.spark layout template

Listing 10.15. Spark view for the Index action

Chapter 11. Security

Listing 11.1. Authentication with AuthorizeAttribute

Listing 11.2. User authorization with AuthorizeAttribute

Listing 11.3. Role authorization with AuthorizeAttribute

Listing 11.4. Declaring the IAuthorizationFilter

Listing 11.5. Setting an insecure cookie with “secret” data

Listing 11.6. A malicious comment

Listing 11.7. Nefarious script in HTML

Listing 11.8. Disabling input validation

Listing 11.9. This XSRF example page can be used to breach security

Listing 11.10. Preventing XSRF attacks

Listing 11.11. Using the Html.AntiForgeryToken() helper

Listing 11.12. Requesting JSON data via POST

Listing 11.13. Directing JsonResult to accept GETs

Listing 11.14. Creating a SecureJsonResult to encapsulate serialization logic

Listing 11.15. Consuming SecureJsonResult with jQuery

Chapter 12. Ajax in ASP.NET MVC

Listing 12.1. A simple HTML page

Listing 12.2. Simple JavaScript file

Listing 12.3. A custom Ajax HttpHandler

Listing 12.4. JavaScriptThe view, which remains simple

Listing 12.5. The jQuery script that sets up the form hijacking

Listing 12.6. The actions for SessionController

Listing 12.7. A JSON string representing a speaker

Listing 12.8. The controller action before any modifications

Listing 12.9. A modified controller action that accepts an optional format

Listing 12.10. Hooking up click behavior on each of the links

Listing 12.11. When the user clicks on the link

Listing 12.12. Creating the HTML to display the speaker details

Chapter 13. Controller factories

Listing 13.1. A custom controller factory

Listing 13.2. A controller that accepts dependencies in its constructor

Listing 13.3. Initializing StructureMap in a bootstrapper class

Listing 13.4. A StructureMap registry for our components

Listing 13.5. A simple interface and concrete implementation

Listing 13.6. Dependencies accepted as constructor arguments

Listing 13.7. A StructureMap controller factory

Listing 13.8. A Ninject module used to register dependencies

Listing 13.9. A custom IMessageProvider for Ninject

Listing 13.10. Bootstrapping Ninject

Listing 13.11. Creating a ControllerFactory for Ninject

Listing 13.12. Bootstrapping Windsor

Listing 13.13. A Windsor-specific IMessageProvider

Listing 13.14. A Windsor controller factory

Chapter 14. Model binders and value providers

Listing 14.1. The IFilteredModelBinder interface

Listing 14.2. A smarter model binder

Listing 14.3. The EntityModelBinder

Listing 14.4. The common repository interface

Listing 14.5. The nongeneric repository interface

Listing 14.6. Replacing the default model binder

Listing 14.7. Controller action with an entity as a parameter

Listing 14.8. The IValueProvider interface

Listing 14.9. The ValueProviderFactories class

Listing 14.10. Registering our custom value provider factory

Listing 14.11. The SessionValueProviderFactory class

Listing 14.12. The SessionValueProvider class and constructor

Listing 14.13. The local values cache and AddValues method

Listing 14.14. The ContainsPrefix and GetValue methods

Listing 14.15. Adding the current user’s Profile to Session

Listing 14.16. The key value used for Session

Listing 14.17. A LogOnWidget child action for displaying current user information

Listing 14.18. The LogOnWidgetModel with a CurrentUser member

Chapter 15. Validation

Listing 15.1. Decorating our model with Data Annotations attributes

Listing 15.2. The Edit view using editor templates for displaying validation messages

Listing 15.3. Handling validation errors in our controller action

Listing 15.4. The abstract ModelMetadataProvider class

Listing 15.5. Our custom, conventions-based model metadata provider

Listing 15.6. The ToSeparatedWords extension method

Listing 15.7. Configuring the new ModelMetadataProvider

Listing 15.8. The master page with script files included

Listing 15.9. Enabling client validation in our view

Chapter 16. Routing

Listing 16.1. HTTP headers returned for an .html file

Listing 16.2. Implementing default routes

Listing 16.3. An action method matching http://example.com/users/edit/5

Listing 16.4. A static route

Listing 16.5. Implementation of routes 3 and 4

Listing 16.6. The controller action handling the dynamic routes

Listing 16.7. Shopping basket and checkout rules

Listing 16.8. The catchall route

Listing 16.9. The controller action for the HTTP 404 custom error

Listing 16.10. Testing routes, which can be painful

Listing 16.11. Cleaner route testing with MvcContrib’s TestHelper project

Listing 16.12. Testing our example routes

Listing 16.13. Configuration for the UrlRoutingModule

Listing 16.14. Configuration for IIS 7 Integrated mode

Listing 16.15. A simple custom route handler

Chapter 17. Deployment techniques

Listing 17.1. Setting the environment configuration in Dev.bat

Listing 17.2. Bootstrapper CommonDeploy.bat file overriding NAnt properties

Listing 17.3. Deployment.build NAnt script with the deploy target

Listing 17.4. Using Web Deploy to remotely execute a deployment

Chapter 18. Mapping with AutoMapper

Listing 18.1. An introductory mapping

Listing 18.2. Flattening a simple hierarchy

Listing 18.3. Working with the domain model

Listing 18.4. Mapping objects by hand

Listing 18.5. Working with the manually mapped presentation model

Listing 18.6. A quick look at AutoMapper configuration code

Listing 18.7. AutoMapper initialization

Listing 18.8. Creating a sample profile

Listing 18.9. Examining a potentially dangerous typo

Listing 18.10. Asserting AutoMapper is configured correctly

Listing 18.11. Examining the IValueFormatter interface

Listing 18.12. Implementing IValueFormatter on the BaseFormatter class

Listing 18.13. Deriving NameFormatter to handle combining properties

Listing 18.14. The final view markup

Chapter 19. Lightweight controllers

Listing 19.1. A heavyweight controller

Listing 19.2. A simpler action after refactoring architecture by tiers

Listing 19.3. Applying an action filter to a controller action

Listing 19.4. A custom action filter that adds data to the ViewData dictionary

Listing 19.5. Extending ControllerActionInvoker to provide custom action filters

Listing 19.6. Using our custom action invoker with a custom controller factory

Listing 19.7. Setting the factory function to use the IoC tool

Listing 19.8. An interface to define our custom filter

Listing 19.9. Our custom, non-attribute-based action filter

Listing 19.10. An action filter that uses AutoMapper

Listing 19.11. An action result that applies AutoMapper to the model

Listing 19.12. Using AutoMappedViewResult in an action

Listing 19.13. Sending a message on an application bus

Listing 19.14. IHandler<T> indicates a type that can handle a message type

Listing 19.15. Concrete message handler

Listing 19.16. A command-executing action result

Listing 19.17. Using CommandResult in an action

Chapter 20. Full system testing

Listing 20.1. A first pass at our UI test

Listing 20.2. Creating our base test class

Listing 20.3. The ProductEditTester class, modified to use the base test class

Listing 20.4. Adding the rel attribute to the Products link

Listing 20.5. The LocalSiteMap class

Listing 20.6. The UI test using a helper method to navigate links

Listing 20.7. The NavigateLink method in our WebTestBase class

Listing 20.8. The strongly typed view using editor templates

Listing 20.9. Using a fluent API and expression-based syntax to fill out forms

Listing 20.10. The ForForm method on the WebTestBase class

Listing 20.11. The FluentForm class and constructor

Listing 20.12. The expression-based WithTextBox method

Listing 20.13. The FluentForm Save method

Listing 20.14. Providing a page indicator in our markup

Listing 20.15. Site structure in a well-formed object model

Listing 20.16. Asserting for a specific page

Listing 20.17. The CurrentPageShouldBe method

Listing 20.18. Using expression-based display templates

Listing 20.19. The updated string display template

Listing 20.20. The final test code using expression-based display value assertions

Listing 20.21. The FluentPage class

Chapter 21. Organization with areas

Listing 21.1. The default area registration class

Listing 21.2. The application startup method with route and area registration

Listing 21.3. The Index action in the ProfileController

Listing 21.4. Linking to an action within the same controller and area

Listing 21.5. The Edit view inheriting from the global master page

Listing 21.6. The menu HTML with area route information

Listing 21.7. Our modified logon partial including area information

Listing 21.8. A brittle Edit view with magic strings

Listing 21.9. The original LogOff action

Listing 21.10. Using the generated MVC class to refer to controllers and actions

Listing 21.11. Using the generated HtmlHelper extension methods

Chapter 22. Portable areas

Listing 22.1. Registering a portable area from PortableAreaRegistration

Listing 22.2. Consuming a portable area in a regular ASP.NET MVC 2 project

Listing 22.3. RssWidget registration

Listing 22.4. Passing the contents of the feed to the view

Listing 22.5. View for the RssWidget.Index action

Listing 22.6. Calling an RssWidget HtmlHelper extension

Listing 22.7. Hiding complexity in an HtmlHelper extension method

Listing 22.8. A message handler class

Chapter 23. Data access with NHibernate

Listing 23.1. The Visitor class, the domain model for this example

Listing 23.2. The repository that defines the persistence operations

Listing 23.3. The factory that provides the repository

Listing 23.4. Repository implementation coupled to NHibernate APIs

Listing 23.5. The hibernate.cfg.xml file

Listing 23.6. The VisitorMap.cs file, which contains mapping for the Visitor class

Listing 23.7. A Configuration object that creates a session factory

Listing 23.8. NHibernate, which generates a database from mappings

Listing 23.9. Output from the schema export

Listing 23.10. Integration tests

Listing 23.11. Action filters applied to controller to keep concerns separated

Listing 23.12. Action filters interacting with domain model

Listing 23.13. Displays recent visitors

Listing 23.14. NHibernateModule, which kick-starts NHibernate

Listing 23.15. Session cache that keeps session in HttpContext items

Listing 23.16. A postbuild event that copies assemblies and config files

Chapter 24. Debugging routes

Listing 24.1. MapRoute, used to specify routes

Listing 24.2. A more detailed way of specifying routes

Listing 24.3. Adding another route

Listing 24.4. A controller action that handles the new route

Listing 24.5. A controller action to respond to the default route

Listing 24.6. A custom route handler that creates an associated IHttpHandler

Listing 24.7. Rendering route diagnostic information to the response stream

Listing 24.8. Assigning routes to our custom route handler

Listing 24.9. Switching the IRouteHandler implementation for debug mode

Chapter 25. Customizing Visual Studio for ASP.NET MVC

Listing 25.1. The autogenerated Create view based on the Product object

Chapter 26. Testing practices

Listing 26.1. The default routes in a new application

Listing 26.2. A simplified product controller

Listing 26.3. Testing a blank URL

Listing 26.4. Registering the routes in a setup method

Listing 26.5. Testing the built-in routing scenarios

Listing 26.6. New scenario routing product search terms

Listing 26.7. Additional route for searching products

Listing 26.8. Modifying the action name for an action method

Listing 26.9. A simple action

Listing 26.10. The controller with its dependency

Listing 26.11. Testing our Index action

Listing 26.12. Testing the Edit action when errors are present

Listing 26.13. Testing our controller action when no errors are present

Listing 26.14. Implementation of the Edit action

Listing 26.15. Implementing an entity model binder

Listing 26.16. Test for bad GUID values

Listing 26.17. Modifying the GUID parsing code to handle invalid values

Listing 26.18. Creating a simple action filter

Listing 26.19. Action filter unit test

Chapter 27. Recipe: creating an autocomplete text box

Listing 27.1. Controller and action for displaying our test page

Listing 27.2. Action to find cities from an autocomplete Ajax request

Listing 27.3. CSS used to style the autocomplete results

Listing 27.4. Adding options to the jQuery autocomplete plug-in