Documenti di Didattica
Documenti di Professioni
Documenti di Cultura
NET MVC 2
This document describes new features and improvements introduced in ASP.NET MVC 2.
Introduction ......................................................................................................................................1
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
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:
New Features
This section describes features that have been introduced in the MVC 2 release.
Templated Helpers
Templated helpers let you automatically associate HTML elements for edit and display with data types.
For example, when data of type System.DateTime is displayed in a view, a date-picker UI element can be
automatically rendered. This is similar to how field templates work in ASP.NET Dynamic Data. For more
information, see Using Templated Helpers to Display Data on the MSDN Web site.
Areas
Areas let you organize a large project into multiple smaller sections in order to manage the complexity
of a large Web application. Each section (“area”) typically represents a separate section of a large Web
site and is used to group related sets of controllers and views. For more information, see Walkthrough:
Organizing an ASP.NET MVC Application by Areas on the MSDN Web site.
To create a new area, in Solution Explorer, right-click the project, click Add, and then click Area. This
displays a dialog box that prompts you for the area name. After you enter the area name, Visual Studio
adds a new area to the project.
The following figure shows an example layout for a project with two areas, Admin and Blogs.
namespace MyApplication.Areas.Blog {
public class BlogAreaRegistration : AreaRegistration {
public override string AreaName {
get { return "blog"; }
}
context.MapRoute(
"blog_whatsnew",
The default project template for ASP.NET MVC 2 includes a call to the RegisterAllAreas method in the
code for the Global.asax file. This method registers each area in the project by looking for all types
that derive from the AreaRegistration class, instantiating an instance of the type, and then calling the
RegisterArea method on the instance. The following example shows how this is done.
void App_Start() {
AreaRegistration.RegisterAllAreas();
RegisterRoutes(RouteTable.Routes);
}
If you do not specify the namespace in the RegisterArea method by calling the context.Namespaces.Add
method, the namespace of the registration class is used by default.
{controller}/{action}/{id}
Also assume that the following controller and action method is defined:
Any of the following request URLs will invoke the View action method that is defined in the preceding
example.
/Article/View/123
/Article/View/123?page=1 (Effectively the same as the previous request)
/Article/View/123?page=2
Without the DefaultValueAttribute attribute, the first URL from the preceding list would not work,
because the page argument is a non-nullable value type whose value has not been provided.
If your code is written in Visual Basic 2010 or Visual C# 2010, you can use optional parameters instead of
the DefaultValueAttribute attribute, as shown in the following example:
A typical use is to embed a timestamp for an object in the view. For example, your application might
include the following Product object:
An edit form can render the TimeStamp property in the form as shown in the following example:
This markup renders a hidden input element with the timestamp value as a base-64-encoded string that
resembles the following example:
This form might be posted to an action method that has an argument of type Product, as shown in the
following example:
In the action method, the TimeStamp property is populated correctly because the posted base-64-
encoded string is converted to a byte array.
The ViewDataDictionary class exposes a ModelMetadata object that contains the metadata that is
extracted from the model by the ModelMetadataProvider class. This enables the templated helpers to
consume this metadata and adjust their output accordingly.
For more information, see the documentation for the ModelMetadata and ModelMetadataProvider
classes.
Model-Validator Providers
The model-validation provider class represents an abstraction that provides validation logic for the
model. ASP.NET MVC includes a default provider based on validation attributes that are included in the
System.ComponentModel.DataAnnotations namespace. You can also create your own validation
providers that define custom validation rules and custom mappings of validation rules to the model. For
more information, see the documentation for the ModelValidatorProvider class.
Client-Side Validation
The model-validator provider class exposes validation metadata to the browser in the form of JSON-
serialized data that can be consumed by a client-side validation library. ASP.NET MVC 2 includes a client
validation library and adapter that supports the DataAnnotations namespace validation attributes noted
earlier. 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.
ASP.NET MVC 2 includes new attributes that you can apply to action methods and that feature compact
syntax. These attributes enable ASP.NET MVC to select an action method based on the HTTP verb. In the
[HttpPost]
public ActionResult Edit(int id)
[HttpPut]
public ActionResult Edit(int id, Tag tag)
In earlier versions of ASP.NET MVC, these action methods required more verbose syntax, as shown in
the following example:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(int id)
[AcceptVerbs(HttpVerbs.Put)]
public ActionResult Edit(int id, Tag tag)
Because browsers support only the GET and POST HTTP verbs, it is not possible to post to an action that
requires a different verb. Thus it is not possible to natively support all RESTful requests.
However, to support RESTful requests during POST operations, ASP.NET MVC 2 introduces a new
HttpMethodOverride HTML helper method. This method renders a hidden input element that causes the
form to effectively emulate any HTTP method. For example, by using the HttpMethodOverride HTML
helper method, you can have a form submission appear be a PUT or DELETE request. 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. The override value can also be specified in an HTTP header or in a query string value as a
name/value pair.
The override can only be used when the real request is a POST request. The override value will be
ignored for requests that use any other HTTP verb.
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.
When a view lets users edit a binary property that should never be displayed, such as a timestamp
property. In that case, the value and surrounding HTML markup (such as the label and value) are not
displayed.
[HiddenInput(DisplayValue=false)]
public byte[] TimeStamp { get; set; }
}
When the attribute is set to true (or no parameter is specified), the following occurs:
In display templates, a label is rendered and the value is displayed to the user.
In editor templates, a label is rendered and the value is rendered in a hidden input element.
API Improvements
This section describes changes to existing ASP.NET MVC types and members.
Added a protected virtual CreateActionInvoker method in the Controller 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.
Added a protected virtual HandleUnauthorizedRequest method in the AuthorizeAttribute class. This
enables filters that derive from AuthorizeAttribute to control the behavior when authorization fails.
Added an Add(string key, object value) method in the ValueProviderDictionary class. This enables
you to use the dictionary initializer syntax for ValueProviderDictionary, as in the following example:
Added a get_object method in the Sys.Mvc.AjaxContext class. This is a JavaScript method that is
similar to the get_data method, but if the content type of the response is application/json,
get_object returns the JSON object.
Added an ActionDescriptor property in the AuthorizationContext class.
Added a UrlParameter.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. For more detail, see
the entry ASP.NET MVC 2 Optional URL Parameters on Phil Haack’s blog.
For model objects that use IDataErrorInfo to perform validation, every property is validated, regardless
of whether a new value was set. In ASP.NET MVC 1.0, only properties that had new values set were
validated. In ASP.NET MVC 2, the Error property of IDataErrorInfo is called only if all the property
validators were successful.
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. 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.NET CodePlex site.
Due to changes in the rendering behavior of MVC view engines, the Html.Substitute helper method does
not work and has been removed.
Every property or method argument that accepted IDictionary<string, ValueProviderResult> in MVC 1.0
now accepts IValueProvider. This change affects only applications that include custom value providers or
custom model binders. Examples of properties and methods that are affected by this change include the
following:
The Site.css file in the ASP.NET MVC project templates has been updated to include new styles used by
the validation functionality and by the templated helpers.
In order to take advantage of the new HTML-encoding expression syntax in ASP.NET 4, the return type
for HTML helpers is now MvcHtmlString instead of a string. If you use ASP.NET MVC 2 and the new
In order to mitigate JSON hijacking attacks that have the potential for information disclosure, by default,
the JsonResult class now responds only to HTTP POST requests. Ajax GET calls to action methods that
return a JsonResult object should be changed to use POST instead. If necessary, you can override this
behavior by setting the new JsonRequestBehavior property of JsonResult. For more information about
the potential exploit, see the blog post JSON Hijacking on Phil Haack’s blog.
A new settable ModelMetadata property has been added to the ModelBindingContext class. The new
property encapsulates both the Model and the ModelType properties. Although the Model and
ModelType properties are obsolete, for backward compatibility the property getters still work; they
delegate to the ModelMetadata property to retrieve the value.
Changes to the DefaultControllerFactory class break custom controller factories that derive
from it
The DefaultControllerFactory class was fixed by removing the RequestContext property. In place of this
property, the request context instance is passed to the protected virtual GetControllerInstance and
GetControllerType methods. This change affects custom controller factories that derive from
DefaultControllerFactory.
Custom controller factories are often used to provide dependency injection for ASP.NET MVC
applications. To update the custom controller factories to support ASP.NET MVC 2, change the method
signature or signatures to match the new signatures, and use the request context parameter instead of
the property.
The string “area” in Route values now has special meaning in ASP.NET MVC, in the same way that
“controller” and “action” do. One implication is that if HTML helpers are supplied with a route-value
dictionary containing “area”, the helpers will no longer append “area” in the query string.
If you are using the Areas feature, make sure to not use {area} as part of your route URL.
The information contained in this document represents the current view of Microsoft Corporation on
the issues discussed as of the date of publication. Because Microsoft must respond to changing market
conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft
cannot guarantee the accuracy of any information presented after the date of publication.
This White Paper is for informational purposes only. MICROSOFT MAKES NO WARRANTIES, EXPRESS,
IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS DOCUMENT.
Complying with all applicable copyright laws is the responsibility of the user. Without limiting the rights
under copyright, no part of this document may be reproduced, stored in or introduced into a retrieval
system, or transmitted in any form or by any means (electronic, mechanical, photocopying, recording, or
otherwise), or for any purpose, without the express written permission of Microsoft Corporation.
Microsoft may have patents, patent applications, trademarks, copyrights, or other intellectual property
rights covering subject matter in this document. Except as expressly provided in any written license
agreement from Microsoft, the furnishing of this document does not give you any license to these
patents, trademarks, copyrights, or other intellectual property.
Unless otherwise noted, the example companies, organizations, products, domain names, e-mail
addresses, logos, people, places and events depicted herein are fictitious, and no association with any
real company, organization, product, domain name, email address, logo, person, place or event is
intended or should be inferred.
Microsoft and Windows are either registered trademarks or trademarks of Microsoft Corporation in the
United States and/or other countries.
The names of actual companies and products mentioned herein may be the trademarks of their
respective owners.