What’s New in ASP.

NET MVC 2
This document describes new features and improvements introduced in ASP.NET MVC 2. Introduction ......................................................................................................................................1 Upgrading an ASP.NET MVC 1.0 Project to ASP.NET MVC 2 .................................................................2 New Features.....................................................................................................................................2 Templated Helpers .................................................................................................................................... 2 Areas ......................................................................................................................................................... 2 Support for Asynchronous Controllers ..................................................................................................... 4 Support for DefaultValueAttribute in Action-Method Parameters .......................................................... 4 Support for Binding Binary Data with Model Binders............................................................................... 5 ModelMetadata and ModelMetadataProvider Classes............................................................................ 6 Support for DataAnnotations Attributes .................................................................................................. 6 Model-Validator Providers ........................................................................................................................ 7 Client-Side Validation ................................................................................................................................ 7 New Code Snippets for Visual Studio 2010 ............................................................................................... 7 New RequireHttpsAttribute Action Filter ................................................................................................. 7 Overriding the HTTP Method Verb ........................................................................................................... 7 New HiddenInputAttribute Class for Templated Helpers ......................................................................... 9 Html.ValidationSummary Helper Method Can Display Model-Level Errors ........................................... 10 T4 Templates in Visual Studio Generate Code that is Specific to the Target Version of the .NET Framework .............................................................................................................................................. 10 API Improvements ........................................................................................................................... 10 Breaking Changes............................................................................................................................. 11 Disclaimer........................................................................................................................................ 13

Introduction
ASP.NET MVC 2 builds on ASP.NET MVC 1.0 and introduces a large set of enhancements and features that are focused on increasing productivity. This release is compatible with ASP.NET MVC 1.0, so all your knowledge, skills, code, and extensions for ASP.NET MVC 1.0 continue to apply. For more information about ASP.NET MVC, visit the following resources: What’s New in ASP.NET MVC 2 Copyright © 2010 Microsoft Corporation 1

when data of type System.NET MVC 1. Each section (“area”) typically represents a separate section of a large Web site and is used to group related sets of controllers and views. To create a new area.DateTime is displayed in a view.   ASP. For more information.NET MVC 1. For example.0 Application to ASP.0 on the same server.NET MVC Application by Areas on the MSDN Web site.NET MVC 2 Copyright © 2010 Microsoft Corporation 2 . For information on how to upgrade. and then click Area. see Using Templated Helpers to Display Data on the MSDN Web site.0 application to ASP. in Solution Explorer. New Features This section describes features that have been introduced in the MVC 2 release.NET MVC documentation on MSDN The ASP. After you enter the area name. see the document Upgrading an ASP.NET MVC 1. Templated Helpers Templated helpers let you automatically associate HTML elements for edit and display with data types.NET MVC 2.NET MVC forums Upgrading an ASP. Visual Studio adds a new area to the project. which gives application developers flexibility in choosing when to upgrade an ASP.NET Dynamic Data. a date-picker UI element can be automatically rendered. This is similar to how field templates work in ASP. Areas Areas let you organize a large project into multiple smaller sections in order to manage the complexity of a large Web application.0 Project to ASP. This displays a dialog box that prompts you for the area name. The following figure shows an example layout for a project with two areas. see Walkthrough: Organizing an ASP. right-click the project.NET MVC 2 can be installed side by side with ASP. Admin and Blogs. For more information. click Add.NET MVC 1.NET MVC Web site The ASP.NET MVC 2 ASP.NET MVC 2. What’s New in ASP.

Visual Studio adds a class that derives from AreaRegistration to each area. What’s New in ASP. } } public override void RegisterArea(AreaRegistrationContext context) { context. id = UrlParameter. context. as shown in the following example: namespace MyApplication. new { action = "Index".MapRoute( "blog_default".When you create an area.Optional } ). "blog/{controller}/{action}/{id}".Blog { public class BlogAreaRegistration : AreaRegistration { public override string AreaName { get { return "blog".MapRoute( "blog_whatsnew". This class is required in order to register the area and its routes.Areas.NET MVC 2 Copyright © 2010 Microsoft Corporation 3 .

Support for Asynchronous Controllers ASP. This can lead to performance gains by allowing servers which frequently call blocking operations (like network requests) to call non-blocking counterparts instead.). the namespace of the registration class is used by default. } } If you do not specify the namespace in the RegisterArea method by calling the context.DefaultValueAttribute class allows a default value to be supplied for the argument parameter to an action method.ComponentModel. For example.RegisterAllAreas(). and then calling the RegisterArea method on the instance. new { action = "WhatsNew". This method registers each area in the project by looking for all types that derive from the AreaRegistration class.Optional ). id = UrlParameter.NET MVC 2 Copyright © 2010 Microsoft Corporation 4 . "{controller}/{action}/{id}". For more information.asax file.MapRoute("default". RegisterRoutes(RouteTable. assume that the following default route is defined: {controller}/{action}/{id} Also assume that the following controller and action method is defined: What’s New in ASP. } public static void RegisterRoutes(RouteCollection routes) { routes.Namespaces.. Support for DefaultValueAttribute in Action-Method Parameters The System."whats-new". public class MyMvcApplication : HttpApplication { void App_Start() { AreaRegistration. The following example shows how this is done.NET MVC 2 includes a call to the RegisterAllAreas method in the code for the Global.NET MVC 2 now allows controllers to process requests asynchronously. .Routes). see the Using an Asynchronous Controller in ASP..NET MVC topic on MSDN.Add method. instantiating an instance of the type. } } } } The default project template for ASP.

public static string Hidden(this HtmlHelper htmlHelper.. other properties . public byte[] TimeStamp { What’s New in ASP.. Binary value). because the page argument is a non-nullable value type whose value has not been provided. For example. If your code is written in Visual Basic 2010 or Visual C# 2010. Optional ByVal page As Integer = 1) _ As ActionResult ' .. your application might include the following Product object: public class Product { //...public class ArticleController { public ActionResult View(int id. End Function public ActionResult MyAction(int id. } Support for Binding Binary Data with Model Binders There are two new overloads of the Html. int page = 1) { // . as shown in the following example: Function View(ByVal id As Integer. [DefaultValue(1)]int page) { } } Any of the following request URLs will invoke the View action method that is defined in the preceding example. byte[] value). the first URL from the preceding list would not work. you can use optional parameters instead of the DefaultValueAttribute attribute.NET MVC 2 Copyright © 2010 Microsoft Corporation 5 ..Hidden helper that encode binary values as base-64-encoded strings: public static string Hidden(this HtmlHelper htmlHelper.. string name. A typical use is to embed a timestamp for an object in the view.    /Article/View/123 /Article/View/123?page=1 (Effectively the same as the previous request) /Article/View/123?page=2 Without the DefaultValueAttribute attribute. string name..

Hidden("TimeStamp". Support for DataAnnotations Attributes ASP.get. such as databases or XML files. What’s New in ASP. For more information.TimeStamp is populated from the form } In the action method.DataAnnotations namespace) when you bind to a model in order to provide input validation. and RegexAttribute validation attributes (defined in the System. } } An edit form can render the TimeStamp property in the form as shown in the following example: <%@ Page Inherits="ViewPage<Product>" %> <%= Html. RequiredAttribute.NET MVC 2 Copyright © 2010 Microsoft Corporation 6 . MVC 2 includes a default provider that makes available the metadata that is exposed by the attributes in the System. The ViewDataDictionary class exposes a ModelMetadata object that contains the metadata that is extracted from the model by the ModelMetadataProvider class. see the documentation for the ModelMetadata and ModelMetadataProvider classes. as shown in the following example: public ActionResult Edit(Product p) { // p. StringLengthAttribute.DataAnnotations namespace.ComponentModel. This enables the templated helpers to consume this metadata and adjust their output accordingly. Model.ComponentModel.NET MVC 2 supports using the RangeAttribute. the TimeStamp property is populated correctly because the posted base-64encoded string is converted to a byte array. ModelMetadata and ModelMetadataProvider Classes The ModelMetadataProvider class provides an abstraction for obtaining metadata for the model within a view.TimeStamp) %> This markup renders a hidden input element with the timestamp value as a base-64-encoded string that resembles the following example: <input type="hidden" name="TimeStamp" value="QVNQLk5FVCBNVkMgaXMgZnVuIQ==" /> This form might be posted to an action method that has an argument of type Product. It is possible to create metadata providers that provide metadata from other data stores. set.

ASP. For the language. Client-Side Validation The model-validator provider class exposes validation metadata to the browser in the form of JSONserialized data that can be consumed by a client-side validation library. The provider class also enables you to use other client-validation libraries by writing an adapter that processes the JSON data and calls into the alternate library. and DELETE.com/fwlink/?LinkId=157753. and for location. select ASP. REST requires that applications support the full range of common HTTP verbs.microsoft. Overriding the HTTP Method Verb When you build a Web site by using the REST architectural style. the filter redirects a non-SSL (HTTP) request to the SSL-enabled (HTTPS) equivalent. To view a list of these snippets. ASP.NET MVC 2 includes new attributes that you can apply to action methods and that feature compact syntax. see How to: Validate Model Data Using DataAnnotations Attributes on the MSDN Web site. New Code Snippets for Visual Studio 2010 A set of HTML code snippets for ASP. A sample project that illustrates the use of these attributes is available for download at http://go. By default. in the Tools menu.ComponentModel. see the documentation for the ModelValidatorProvider class. For more information. see the Visual Studio documentation. In the What’s New in ASP. POST. select HTML. HTTP verbs are used to determine which action to perform for a resource.NET MVC 2 is installed with Visual Studio 2010.NET MVC includes a default provider based on validation attributes that are included in the System.NET MVC 2 includes a new RequireHttpsAttribute class that can be applied to action methods and controllers.DataAnnotations namespace. For more information about how to use code snippets.NET MVC 2 includes a client validation library and adapter that supports the DataAnnotations namespace validation attributes noted earlier. Model-Validator Providers The model-validation provider class represents an abstraction that provides validation logic for the model. New RequireHttpsAttribute Action Filter ASP. including GET. These attributes enable ASP.NET MVC 2. PUT.NET MVC to select an action method based on the HTTP verb. ASP.NET MVC 2 Copyright © 2010 Microsoft Corporation 7 . select Code Snippets Manager.For more information. You can also create your own validation providers that define custom validation rules and custom mappings of validation rules to the model.

Tag tag) In earlier versions of ASP. Thus it is not possible to natively support all RESTful requests. as shown in the following example: [AcceptVerbs(HttpVerbs.NET MVC 2 introduces a new HttpMethodOverride HTML helper method. The override value will be ignored for requests that use any other HTTP verb. This method renders a hidden input element that causes the form to effectively emulate any HTTP method. these action methods required more verbose syntax. to support RESTful requests during POST operations. Tag tag) Because browsers support only the GET and POST HTTP verbs. The behavior of HttpMethodOverride affects the following attributes:      HttpPostAttribute HttpPutAttribute HttpGetAttribute HttpDeleteAttribute AcceptVerbsAttribute The hidden input element has its name X-HTTP-Method-Override and its value set to the HTTP verb to emulate.Post)] public ActionResult Edit(int id) [AcceptVerbs(HttpVerbs. The override can only be used when the real request is a POST request.NET MVC. The override value can also be specified in an HTTP header or in a query string value as a name/value pair. For example. However.NET MVC 2 Copyright © 2010 Microsoft Corporation 8 .following example. you can have a form submission appear be a PUT or DELETE request. it is not possible to post to an action that requires a different verb.Put)] public ActionResult Edit(int id. a POST request will call the first action method and a PUT request will call the second action method. What’s New in ASP. ASP. [HttpPost] public ActionResult Edit(int id) [HttpPut] public ActionResult Edit(int id. by using the HttpMethodOverride HTML helper method.

When DisplayValue is set to false.NET MVC 2 Copyright © 2010 Microsoft Corporation 9 . The attribute’s DisplayValue property lets you specify whether the value is displayed in editor and display modes.  The following example shows how to use the HiddenInputAttribute class. such as a timestamp property. When the attribute is set to false. the following occurs:   In display templates. a label is rendered and the value is rendered in a hidden input element. When a view lets users edit a binary property that should never be displayed. In editor templates. In editor templates.New HiddenInputAttribute Class for Templated Helpers You can apply the new HiddenInputAttribute attribute to a model property to indicate whether a hidden input element should be rendered when displaying the model in an editor template. nothing is displayed. no label is rendered and the value is rendered in a hidden input element. the value and surrounding HTML markup (such as the label and value) are not displayed. } } When the attribute is set to true (or no parameter is specified). the following occurs:   In display templates. } [HiddenInput(DisplayValue=false)] public byte[] TimeStamp { get. You might use HiddenInputAttribute attribute in the following scenarios:  When a view lets users edit the ID of an object and it is necessary to display the value as well as to provide a hidden input element that contains the old ID so that it can be passed back to the controller. a label is rendered and the value is displayed to the user. not even the HTML markup that normally surrounds a field. set. What’s New in ASP. The default value for DisplayValue is true. set. nothing is rendered for that field. In that case. (The attribute sets an implicit UIHint value of HiddenInput). public class ProductViewModel { [HiddenInput] // equivalent to [HiddenInput(DisplayValue=true)] public int Id { get. } public string Name { get. set.

but if the content type of the response is application/json.ValidationSummary Helper Method Can Display Model-Level Errors Instead of always displaying all validation errors. API Improvements This section describes changes to existing ASP. T4 Templates in Visual Studio Generate Code that is Specific to the Target Version of the . In Visual Studio 2010. For more detail. Added a UrlParameter.Mvc.ValueProvider = new ValueProviderDictionary(null) { { "example1". get_object returns the JSON object.NET 3. "example1Value" }. What’s New in ASP. object value) method in the ValueProviderDictionary class. This enables filters that derive from AuthorizeAttribute to control the behavior when authorization fails. { "example3". "example2Value" }.NET Framework.ValidationSummary helper method has a new option to display only model-level errors.5 or .NET Framework A new property is available to T4 files from the ASP. see the entry ASP. the value is always .Html. as in the following example: Controller c = new MyController(). the value is either .      Added a get_object method in the Sys.NET MVC types and members.NET 4.NET Framework that is used by the application.NET 3. This enables T4 templates to generate code and markup that is specific to a version of the . Added an Add(string key.NET MVC 2 Copyright © 2010 Microsoft Corporation 10 . the Html. This is a JavaScript method that is similar to the get_data method.  Added a protected virtual CreateActionInvoker method in the Controller class. new int[] { 1. This enables model-level errors to be displayed in the validation summary and field-specific errors to be displayed next to each field.NET MVC 2 Optional URL Parameters on Phil Haack’s blog. 2. Added an ActionDescriptor property in the AuthorizationContext class. In Visual Studio 2008. 3 } } }.AjaxContext class. Added a protected virtual HandleUnauthorizedRequest method in the AuthorizeAttribute class. This method is invoked by the ActionInvoker property of Controller and allows for lazy instantiation of the invoker if no invoker is already set.5. c.Optional token that can be used to work around problems when binding to a model that contains an ID property when the property is absent in a form post.NET MVC T4 host that specifies the version of the . { "example2". This enables you to use the dictionary initializer syntax for ValueProviderDictionary.

Substitute helper method does not work and has been removed. Change in property validation behavior for classes that implement IDataErrorInfo For model objects that use IDataErrorInfo to perform validation.Breaking Changes The following changes might cause errors in existing ASP. The script-mapping script is not needed if you use the Visual Studio Development Server or if you use IIS 7 in Integrated mode. The scripts are available as a separate unsupported download on the ASP.0 applications. every property is validated. the return type for HTML helpers is now MvcHtmlString instead of a string. In ASP.0. The IValueProvider interface replaces all uses of IDictionary<string. New CSS classes were added in the Site. In ASP.NET MVC 2 Copyright © 2010 Microsoft Corporation 11 .css file The Site.NET MVC 1. Helpers now return an MvcHtmlString object In order to take advantage of the new HTML-encoding expression syntax in ASP.NET MVC 2.0 now accepts IValueProvider.NET 4. Examples of properties and methods that are affected by this change include the following:   The ValueProvider property of the ControllerBase and ModelBindingContext classes.Substitute helper method in MVC Futures is no longer available Due to changes in the rendering behavior of MVC view engines. If you use ASP. The TryUpdateModel methods of the Controller class. regardless of whether a new value was set. the Html.css file in the ASP. This change affects only applications that include custom value providers or custom model binders.NET MVC 2 and the new What’s New in ASP.NET CodePlex site. The Html. IIS script mapping script is no longer available in the installer The IIS script-mapping script is a command-line script that is used to configure script maps for IIS 6 and for IIS 7 in Classic mode.NET MVC project templates has been updated to include new styles used by the validation functionality and by the templated helpers. ValueProviderResult> Every property or method argument that accepted IDictionary<string. the Error property of IDataErrorInfo is called only if all the property validators were successful.NET MVC 1. ValueProviderResult> in MVC 1. only properties that had new values set were validated.

NET MVC 2. To update the custom controller factories to support ASP. Although the Model and ModelType properties are obsolete. For more information about the potential exploit. change the method signature or signatures to match the new signatures. Model and ModelType property setters on ModelBindingContext are obsolete A new settable ModelMetadata property has been added to the ModelBindingContext class. in the same way that “controller” and “action” do. Changes to the DefaultControllerFactory class break custom controller factories that derive from it The DefaultControllerFactory class was fixed by removing the RequestContext property.5. “Area” is a now a reserved route-value key The string “area” in Route values now has special meaning in ASP. see the blog post JSON Hijacking on Phil Haack’s blog. you can override this behavior by setting the new JsonRequestBehavior property of JsonResult. they delegate to the ModelMetadata property to retrieve the value.NET MVC 2 Copyright © 2010 Microsoft Corporation 12 . the helpers will no longer append “area” in the query string. The new property encapsulates both the Model and the ModelType properties.NET MVC 2 on ASP. you will not be able to take advantage of the HTML-encoding syntax. for backward compatibility the property getters still work. by default. make sure to not use {area} as part of your route URL. What’s New in ASP. In place of this property. If you are using the Areas feature. JsonResult now responds only to HTTP POST requests In order to mitigate JSON hijacking attacks that have the potential for information disclosure. the new syntax is available only when you run ASP. If necessary.NET 3. One implication is that if HTML helpers are supplied with a route-value dictionary containing “area”. the JsonResult class now responds only to HTTP POST requests. This change affects custom controller factories that derive from DefaultControllerFactory.helpers on ASP. the request context instance is passed to the protected virtual GetControllerInstance and GetControllerType methods.NET MVC. and use the request context parameter instead of the property. Ajax GET calls to action methods that return a JsonResult object should be changed to use POST instead. Custom controller factories are often used to provide dependency injection for ASP.NET MVC applications.NET 4.

without the express written permission of Microsoft Corporation. logo. domain name. The information contained in this document represents the current view of Microsoft Corporation on the issues discussed as of the date of publication. AS TO THE INFORMATION IN THIS DOCUMENT. Except as expressly provided in any written license agreement from Microsoft. mechanical. patent applications. e-mail addresses. or transmitted in any form or by any means (electronic. MICROSOFT MAKES NO WARRANTIES. stored in or introduced into a retrieval system. IMPLIED OR STATUTORY. © 2010 Microsoft Corporation. Without limiting the rights under copyright. Microsoft and Windows are either registered trademarks or trademarks of Microsoft Corporation in the United States and/or other countries. copyrights. logos. email address. EXPRESS. it should not be interpreted to be a commitment on the part of Microsoft. The names of actual companies and products mentioned herein may be the trademarks of their respective owners. This White Paper is for informational purposes only. photocopying. trademarks. or other intellectual property.Disclaimer This is a preliminary document and may be changed substantially prior to final commercial release of the software described herein. Because Microsoft must respond to changing market conditions. product.NET MVC 2 Copyright © 2010 Microsoft Corporation 13 . organization. the example companies. place or event is intended or should be inferred. or for any purpose. person. Microsoft may have patents. no part of this document may be reproduced. trademarks. recording. Unless otherwise noted. Complying with all applicable copyright laws is the responsibility of the user. places and events depicted herein are fictitious. products. organizations. domain names. What’s New in ASP. and no association with any real company. copyrights. or other intellectual property rights covering subject matter in this document. the furnishing of this document does not give you any license to these patents. and Microsoft cannot guarantee the accuracy of any information presented after the date of publication. All rights reserved. or otherwise). people.