ࡱ > y bjbj 4v ȉ ȉ
n ) ) 7 7 7 7 7 7 7 7 8 S7 \ 9 7 w k: E@ [@ [@ [@ A oG I $ / * 7 I A A I I 7 7 [@ [@ h 1 M M M I z 7 [@ 7 [@ M I M M P T [@ va 7 UL v \ G 0 w Y L Y B Y 7 # I I M I I I I I M I I I w I I I I Y I I I I I I I I I ) 5 : ASP.NET MVC RC Release Notes
This document describes changes that have been made to the ASP.NET MVC framework since the Beta release. It also describes changes that you must make in existing MVC applications to run with the new release.
TOC \o "1-2" \h \z \u HYPERLINK \l "_Toc221002665" Whats New PAGEREF _Toc221002665 \h 3
HYPERLINK \l "_Toc221002666" Release Candidate MSI Installer Notes PAGEREF _Toc221002666 \h 3
HYPERLINK \l "_Toc221002667" Uninstalling the Release Candidate PAGEREF _Toc221002667 \h 3
HYPERLINK \l "_Toc221002668" GAC Assemblies PAGEREF _Toc221002668 \h 3
HYPERLINK \l "_Toc221002669" Script for Registering .mvc Extensions PAGEREF _Toc221002669 \h 4
HYPERLINK \l "_Toc221002670" Native Code Support PAGEREF _Toc221002670 \h 5
HYPERLINK \l "_Toc221002671" Template and Tool Changes Made Since ASP.NET MVC Beta PAGEREF _Toc221002671 \h 5
HYPERLINK \l "_Toc221002672" Specifying View Types in Page Directives PAGEREF _Toc221002672 \h 5
HYPERLINK \l "_Toc221002673" New Empty ContentPlaceholder Control in the
Section of the Site.master Template PAGEREF _Toc221002673 \h 5
HYPERLINK \l "_Toc221002674" FieldSet-based HTML Layout for LogOn, Register, and ChangePassword Pages PAGEREF _Toc221002674 \h 5
HYPERLINK \l "_Toc221002675" Overriding "Add View" and "Add Controller" Code Generation in an MVC Project PAGEREF _Toc221002675 \h 8
HYPERLINK \l "_Toc221002676" New Go To View Command in Visual Studio PAGEREF _Toc221002676 \h 9
HYPERLINK \l "_Toc221002677" New Go To Controller Command in Visual Studio PAGEREF _Toc221002677 \h 9
HYPERLINK \l "_Toc221002678" MVC File Refactoring in Visual Studio PAGEREF _Toc221002678 \h 9
HYPERLINK \l "_Toc221002679" ASP.NET Compiler Post-Build Step PAGEREF _Toc221002679 \h 11
HYPERLINK \l "_Toc221002680" Run-Time Changes Made Since ASP.NET MVC Beta PAGEREF _Toc221002680 \h 12
HYPERLINK \l "_Toc221002681" New BeginRouteForm Extension Methods Added to HtmlHelper PAGEREF _Toc221002681 \h 12
HYPERLINK \l "_Toc221002682" IsMvcAjaxRequest Renamed to IsAjaxRequest PAGEREF _Toc221002682 \h 12
HYPERLINK \l "_Toc221002683" jQuery IntelliSense Files Included in the Project Template PAGEREF _Toc221002683 \h 12
HYPERLINK \l "_Toc221002684" Changes Made to DropDownList and ListBox Method PAGEREF _Toc221002684 \h 12
HYPERLINK \l "_Toc221002685" Helpers Added for Preventing CSRF Attacks PAGEREF _Toc221002685 \h 13
HYPERLINK \l "_Toc221002686" File Helper and FileResult Types Added for Returning Binary Content from an Action Method. PAGEREF _Toc221002686 \h 14
HYPERLINK \l "_Toc221002687" ControllerContext Changed to No Longer Derive from RequestContext PAGEREF _Toc221002687 \h 14
HYPERLINK \l "_Toc221002688" Form Helpers Changed to Replace Dots with Underscores When Rendering the ID Attribute PAGEREF _Toc221002688 \h 14
HYPERLINK \l "_Toc221002689" [Bind(Prefix="")] No Longer Required in Common Scenarios PAGEREF _Toc221002689 \h 15
HYPERLINK \l "_Toc221002690" Model Binder API Changes PAGEREF _Toc221002690 \h 17
HYPERLINK \l "_Toc221002691" Model Binder Support Added for IDataErrorInfo PAGEREF _Toc221002691 \h 18
HYPERLINK \l "_Toc221002692" Descriptor Types Added PAGEREF _Toc221002692 \h 20
HYPERLINK \l "_Toc221002693" HtmlHelper Class Added PAGEREF _Toc221002693 \h 20
HYPERLINK \l "_Toc221002694" New JavaScriptResult Action Result and JavaScript Controller Method Added PAGEREF _Toc221002694 \h 21
HYPERLINK \l "_Toc221002695" Bug Fixes Since Beta PAGEREF _Toc221002695 \h 21
HYPERLINK \l "_Toc221002696" Upgrading from the Beta Release to the Release Candidate PAGEREF _Toc221002696 \h 23
HYPERLINK \l "_Toc221002697" Known Issue with the RC PAGEREF _Toc221002697 \h 24
HYPERLINK \l "_Toc221002698" Known Installer Issues PAGEREF _Toc221002698 \h 24
HYPERLINK \l "_Toc221002699" Conflict with Visual Studio Add-Ins PAGEREF _Toc221002699 \h 24
HYPERLINK \l "_Toc221002700" Cryptographic Services PAGEREF _Toc221002700 \h 25
HYPERLINK \l "_Toc221002701" Visual Studio Templates PAGEREF _Toc221002701 \h 25
Whats New
ASP.NET MVC RC is an officially supported Release Candidate for the ASP.NET MVC framework. As always, feel free to provide feedback on the HYPERLINK "http://forums.asp.net/1146.aspx"ASP.NET MVC forums.
NoteBefore you run the ASP.NET MVC RC installer, uninstall any earlier previews or Beta releases of ASP.NET MVC. In addition, close all instances of Visual Studio 2008.
This section provides information about the new and changed features in this release since the Beta release.
Release Candidate MSI Installer Notes
Uninstalling the Release Candidate
If you use the Microsoft Windows installer (.msi file) to uninstall the RC release, the installer fails to uninstall some template files. This is a known issue that will be fixed for the final RTM release. To uninstall the MVC RC release, use the Add/Remove programs application in the Windows Control Panel.
GAC Assemblies
As with the Beta release, the RC installer installs the ASP.NET MVC assemblies (System.Web.Mvc.dll, System.Web.Routing.dll, and System.Web.Abstractions.dll) into the GAC. Prior to the Beta, these were not installed into the GAC. Because of this change, the default project templates do not automatically copy the assembly into the Bin folder of your application.
The installer also copies the assemblies to the following folder:
%ProgramFiles%\Microsoft ASP.NET\ASP.NET MVC RC\Assemblies\
Even though the installer installs the assemblies to the GAC by default, you can copy the assemblies to an application's Bin folder. This lets you deploy your application to a hosting provider that supports ASP.NET 3.5 but has not installed ASP.NET MVC RC. In other words, ASP.NET 3.5 SP1 is not required in order to host an ASP.NET MVC application.
For information about how to deploy an ASP.NET MVC application with assemblies in the Bin folder, see HYPERLINK "http://haacked.com/archive/2008/11/03/bin-deploy-aspnetmvc.aspx"Bin Deploying ASP.NET MVC on Phil Haack's blog.
Script for Registering .mvc Extensions
Previous releases of MVC automatically registered the .mvc extension in IIS during the installation process. As of this release, the registration no longer occurs automatically. Instead, script files are provided that you can use to perform the registration. The script files will be installed in the following location:
%ProgramFiles%\Microsoft ASP.NET\ASP.NET MVC RC\Scripts
The scripts are there as a convenience for those who want to use .mvc URL extensions within their ASP.NET MVC site in IIS 6 or in IIS 7 Classic mode.
NoteYou do not need to use these scripts if you running an ASP.NET MVC application under IIS 7 in Integrated mode. You also dont need to run these scripts if you choose not to use the .mvc extension for URLs.
The following table lists the scripts.
ScriptDescriptionregistermvc.wsfRegisters the .mvc extension in IIS and associates it with the aspnet_isapi.dll.unregistermvc.wsfUnregisters the .mvc extension in IIS.iismap.vbsCalled by the other scripts. Do not run this script directly.To register the module mapping, execute registermvc.wsf from a command prompt.
NoteRunning these scripts requires Administrator privileges.
Execute the unregistermvc.wsf script to remove the mapping. Use cscript.exe when running the scripts, as shown in the following example:
cscript registermvc.wsf
If you uninstall ASP.NET MVC, you can either remove the mapping prior to uninstalling by using unregistermvc.wsf, or manually remove it by using IIS Manager.
Native Code Support
The installer creates native-code images for System.Web.Mvc during the installation process by using the native image generator tool ( HYPERLINK "http://msdn.microsoft.com/en-us/library/6t9t5wcf(VS.80).aspx" Ngen.exe). On 64-bit computers, both 32-bit and 64-bit native images are produced.
Template and Tool Changes Made Since ASP.NET MVC Beta
Specifying View Types in Page Directives
The templates for ViewPage, ViewMasterPage, and ViewUserControl (and derived types) now support language-specific generic syntax in the main directives Inherits attribute. For example, you can specify the following type in the @Master directive:
<%@ Master Inherits="ViewMasterPage" %>
An alternative approach is to add markup like the following to your page (or to the content area for a content page), although doing so should never be necessary.
The default MVC project templates for Visual Basic and C# views have been updated to incorporate this change to the Inherits attribute. All existing views will still work. If you choose not to use the new syntax, you can still use the earlier syntax in code.
New Empty ContentPlaceholder Control in the Section of the Site.master Template
An empty placeholder in the section of the default master page makes it easier to control the title, style sheets, and scripts that are rendered in the section from an individual content page. The default templates have been updated to use this new content section by specifying the element in the ViewPage view instead of in the Site.master file.
FieldSet-based HTML Layout for LogOn, Register, and ChangePassword Pages
The markup in the LogOn.aspx, Register.aspx, and ChangePassword.aspx pages has been modified to use elements for layout instead of using a element.
New "Add Controller" Command in Visual Studio
A new Add Controller command is available by right-clicking the Controllers folder in Solution Explorer or by using the keyboard shortcut CTRL+M, CTRL+-C.
INCLUDEPICTURE "cid:image001.png@01C960DF.B48C0AE0" \* MERGEFORMATINET
In addition to allowing you to specify a Controller name, this dialog box lets you specify that you want to generate stub methods in the controller for data scaffolding operations, such as Create, Update, and Details scenarios.
The code generation for this command is implemented by using the T4 templating engine. You can modify the code that is generated declaratively by modifying the Controller.tt file at the following location:
\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Web\MVC\CodeTemplates\AddController
New "Add View" Command in Visual Studio
A new Add View command is available by right-clicking inside a controllers action method, by right-clicking the Views folder in Solution Explorer, or by using the keyboard shortcut CTRL+M, CTRL+V.
INCLUDEPICTURE "cid:image002.png@01C960DF.B48C0AE0" \* MERGEFORMATINET
In addition to allowing you to specify a view name, the dialog box for this command supports the following features:
Generates either a ViewPage or ViewUserControl class (partial view).
Optionally creates a strongly-typed view based on a specified ViewData type.
Optionally generates view content based on the specified ViewData type. The supported contents are List, Edit, Create, and Details. Content is supported only when you choose a ViewData type from the available types in the list.
Optionally lets you specify a master page for the view, along with the default ContentPlaceholder control to use when generating content for the view.
The code generation for this command is implemented using by the T4 templating engine. You can edit the code that is generated declaratively by modifying the files at the following location:
\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Web\MVC\CodeTemplates\AddView
You can optionally create additional files (in *.tt format) in this folder, and they will be automatically displayed in the View content list in the dialog box.
Overriding "Add View" and "Add Controller" Code Generation in an MVC Project
By default, the code generation for the Add View and Add Controller commands is driven by a set of *.tt format files that in subfolders under the following folder:
\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Web\MVC\CodeTemplates
Modifying the files at this location customizes the code generation for the Add View and Add Controller commands globally for any MVC project on the computer. You can also override the code generation on a per-project basis by using the following steps:
In Windows Explorer, copy the entire CodeTemplates folder from the following location to the root folder for your project:
\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Web\MVC\CodeTemplates
In Solution Explorer in Visual Studio, paste this folder to the root of your MVC Project
Edit the content of the *.tt files in the CodeTemplates folder of your project.
Visual Studio automatically associates the *.tt files to a custom tool (single-file generator) named TextTemplatingFileGenerator. These *.tt files are intended to be run only in the context of the Add View and Add Controller commands, where an MvcTextTemplateHost object is made available to the template. Executing the custom tool for these templates will fail, and will produce errors in the Visual Studio Error List window.
NoteVisual Web Developer Express Edition does not automatically associate the .ttf extension to the single-file generator, so you do not need to manually disassociate the extension in the Express Edition.
To prevent the single-file generator from running for *.tt files, you must remove the association to the Custom Tool property manually by following these steps:
For each *.tt file in the CodeTemplates folder, set the Custom Tool property to an empty string.
Close and reopen the MVC project to clear the Error List window. (This works around a known bug.)
New Go To View Command in Visual Studio
Navigating between a controller action method and view is made easier by the addition of a new Go To View command, which is available in any context where the Add View command is available. The shortcut key for this command is CTRL+M CTRL+G (scoped to the code editor).
When you invoke this command, the active document navigates to the view that has the same name as the current action method. The command looks for the view by using the following order of precedence (which is the same order that is used at run time):
View.aspx in the ~/Views/Controller folder.
View.ascx in the ~/Views/Controller folder.
View.aspx in the ~/Views/Shared folder.
View.ascx in the ~/Views/Shared folder.
New Go To Controller Command in Visual Studio
Visual Studio provides a Go To Controller command that is similar to the Go To View command. The Go To Controller command navigates from a view page or user control to the default controller associated with the view. The shortcut key for this command is CTRL+M CTRL+G (scoped to the HTML editor).
The Go To Controller command is available anywhere within the HTML editor for a view page or user control. The target controller is determined by the containing folder for the view. For example, if the view is in ~/Views/Categories, the Go To View command navigates to the CategoriesController.cs file in the Controllers folder.
MVC File Refactoring in Visual Studio
Because of the convention-based structure of an MVC application, it is possible to move or rename related folders and files when the names of corresponding classes are changed. To facilitate this task, Visual Studio provides the following new file-refactoring features:
Renaming a controller class renames the folder that contains corresponding views, if the folder exists. The following figure shows the correspondence that involves refactoring.
Renaming an action method renames the corresponding view page (.aspx only), if that view exists. The following figure shows the correspondence that involves this refactoring.
NoteIn order for Visual Studio to perform the appropriate refactoring, you must rename the class or action method by using the Rename command (available in the Refactor menu or when the smart tag is displayed in response to typing a new name in the editor).
ASP.NET Compiler Post-Build Step
Currently, errors within a view file are not detected until run time. To let you detect these errors at compile time, ASP.NET MVC projects now include an MvcBuildViews property, which is disabled by default. To enable this property, open the project file and set the MvcBuildViews property to true, as shown in the following example:
true
NoteEnabling this feature adds some overhead to the build time.
You can update projects that were created with previous releases of MVC to include build-time validation of views by performing the following steps:
Open the project file in a text editor.
Add the following element under the top-most element:
true
At the end of the project file, uncomment the element and modify it to match the following example:
Run-Time Changes Made Since ASP.NET MVC Beta
The most recent official release of ASP.NET MVC before the current release was ASP.NET MVC Beta. This section describes changes and bug fixes that have been made since the Beta release.
New BeginRouteForm Extension Methods Added to HtmlHelper
New BeginRouteForm extension methods have been added that are equivalent to the existing BeginForm extension methods, but allow you to specify a route name when you generate the URL that the form posts to.
IsMvcAjaxRequest Renamed to IsAjaxRequest
The IsMvcAjaxRequest method been renamed to IsAjaxRequest. As part of this change, the IsAjaxRequest method was updated to recognize the X-Requested-With HTTP header. This is a well known header sent by the major JavaScript libraries such as Prototype.js, jQuery, and Dojo.
The ASP.NET AJAX helpers were updated to send this header in requests. However, they continue to also send it in the body of the form post in order to work around the issue of firewalls that strip unknown headers.
jQuery IntelliSense Files Included in the Project Template
The Beta release of ASP.NET MVC included the jQuery script file. With the RC, IntelliSense support for jQuery is included in the project templates. To enable jQuery IntelliSense, you must apply a hotfix to Visual Studio 2008 SP1. For more information, see HYPERLINK "http://blogs.msdn.com/webdevtools/archive/2008/11/07/hotfix-to-enable-vsdoc-js-intellisense-doc-files-is-now-available.aspx" VS2008 SP1 Hotfix to Support "-vsdoc.js" IntelliSense Doc Files in the Visual Studio team blog.
Changes Made to DropDownList and ListBox Method
The overloads for DropDownList and ListBox helper methods were reworked to fix various usability problems that were reported by customers.
Previously, these methods accepted only SelectList and MultiSelectList types as arguments to populate the list. You can now pass an enumeration of ListItem, which makes it possible to use LINQ to transform an IEnumerable object into an IENumerable object. The following example demonstrates a transform of IEnumerable into IEnumerable.
IEnumerable peopleList =
from person in db.People
select new SelectListItem {
Text = (person.FirstName + " " + person.LastName),
Value = person.SSN,
Selected = (person.SSN == selectedSSN)
};
Helpers Added for Preventing CSRF Attacks
Cross-site request forgery (CSRF) attacks (also referred to as XSRF attacks) cause users of a trusted browser agent to take unintended actions on a site. These attacks rely on the fact that the user might still be logged in to another site. A malicious Web site exploits this by creating a request to the original site; the request is made by using the users browser and thus with the users authentication token and credentials. The attacker hopes that the users session cookie (hence authentication) is still valid and if so, the attacker can take disruptive action.
The CSRF helpers in ASP.NET MVC represent a two-pronged approach designed to help mitigate CSRF attacks. The first part of the mitigation is to use the Html.AntiForgeryToken helper to render a hidden input token within the form, as shown in the following example:
<% using(Html.Form()) { %>
<%= Html.AntiForgeryToken() %>
<% } %>
This issues a cookie and renders a hidden input element. A malicious Web site will not have both pieces of information.
The second part of the mitigation is to apply an anti-forgery filter to the action method you want to protect, as shown in the following example:
[ValidateAntiForgeryToken]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Product product) {
//Some code
}
This will check for the existence of the token and thereby reduce the chance that a CSRF attack will be successful.
File Helper and FileResult Types Added for Returning Binary Content from an Action Method.
The new File helper method is used to add binary content to the response, as shown in the following example:
return File(@"c:\temp\test.png");
FileResult is an abstract base class. Depending on which overload of the File method is called, one of the following FileResult derived types will be returned:
FilePathResult. This writes a file specified by using a file path to the response.
FileStreamResult. This writes a stream to the response.
FileContentResult. This writes a byte array to the response.
ControllerContext Changed to No Longer Derive from RequestContext
The ControllerContext class now encapsulates RequestContext and exposes it by using a property, instead of deriving from it. Additionally, many properties of ControllerContext and its derived types are now virtual instead of sealed. These changes make it easier to create mock objects based on these types, and they greatly simplify writing many types of unit tests.
Form Helpers Changed to Replace Dots with Underscores When Rendering the ID Attribute
The TextBox helper method can accept an ID that contains a dot, as in the following example:
<%= Html.TextBox("Person.FirstName") %>
In previous versions of ASP.NET MVC, the rendered HTML output for this syntax was as follows:
However, having a dot in the ID attribute makes it more cumbersome to use selectors in jQuery. To select the example input element requires the following jQuery code:
$("#Person\\.FirstName")
In this release, by default the dot character is automatically replaced with an underscore in the value of the ID attribute. Thus the example TextBox renders the following markup:
To change the default replacement character, you can set the HtmlHelper.IDDotReplacementChar property to the character that you want to use instead.
Note that you always have full control over the rendered ID attribute value. If you want the ID value to be something other than the field name value that you pass to the helper method, you can use syntax such as the following:
<%= Html.TextBox("Person.FirstName", null, new {id="pfirst"}) %>
[Bind(Prefix="")] No Longer Required in Common Scenarios
In this release, it is no longer necessary to explicitly set a prefix to an empty string ("") in BindAttribute (or to use BindAttribute at all) in order to prevent the prefix from being used to resolve entity names in an action method. This is best described by illustrating the scenario that this fix solves.
Suppose you have an action method that renders an edit form for products by using a strongly typed view, as in the following example:
public ActionResult Edit(int id) {
//Some code
Product product = someRepository.GetProductById();
return View(product);
}
When you create the markup for a form, you might use helpers like those in the following example:
Name: <%= Html.TextBox("ProductName") %>
Price: <%= Html.TextBox("UnitPrice") %>
Notice that the field names do not have prefixes. This is because the expressions bind directly to the strongly typed model object.
Now suppose you want to post this form to an action method that accepts a product object, as in the following example:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit(Product product) {
//Some code
}
By default, when the action method tries to bind to the product argument, it uses the name of the argument as a prefix. In this case, the action method is expecting the fields product.ProductName and product.UnitPrice. However, the view is sending ProductName and UnitPrice.
The solution up until now was to apply the BindAttribute attribute to the action method in order to explicitly set the prefix to an empty string, as in the following example:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Edit([Bind(Prefix = "")]Product product) {
//Some code
}
Alternatively, you could avoid using a strongly typed view in the original action method and instead add the product to the ViewData object before rendering the view, as in the following example:
public ActionResult Edit(int id) {
//Some code
Product product = someRepository.GetProductById();
ViewData["product"] = product;
return View();
}
In this case, you could then use the prefix in the helpers within your view, as shown in the following example:
Name: <%= Html.TextBox("product.ProductName") %>
Price: <%= Html.TextBox("product.UnitPrice") %>
However, the first approach is the more common approach, and requires the additional work of always specifying a blank prefix. To eliminate this work, the behavior when binding a parameter like this has been changed.
If there is no BindAttribute attribute, the default model binder first looks for any fields within the value provider (that is, any form values) that start with that prefix. If any exist, it binds only to values by using that prefix (such as product.ProductName and product.UnitPrice). If no values exist that have the prefix, the binder falls back to values without a prefix (such as ProductName and UnitPrice). This enables the first scenario to not require BindAttribute at all.
If BindAttribute is present with the Prefix property set to a non-null value, that prefix is used and there is no fallback behavior.
Model Binder API Changes
The DefaultModelBinder class has been refactored to add extensibility points for custom binding and validation schemes. The following example shows the new signatures.
public class DefaultModelBinder : IModelBinder {
public virtual object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext);
protected virtual void BindProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor);
protected virtual object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType);
protected virtual PropertyDescriptorCollection GetModelProperties(ControllerContext controllerContext, ModelBindingContext bindingContext);
protected virtual void OnModelUpdated(ControllerContext controllerContext, ModelBindingContext bindingContext);
protected virtual bool OnModelUpdating(ControllerContext controllerContext, ModelBindingContext bindingContext);
protected virtual void OnPropertyValidated(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value);
protected virtual bool OnPropertyValidating(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value);
protected virtual void SetProperty(ControllerContext controllerContext, ModelBindingContext bindingContext, PropertyDescriptor propertyDescriptor, object value);
}
The order of execution for binding is as follows. To begin, the BindModel method is invoked, which is the entry point to the binder and which is responsible for kicking off the binding process. The rest of the process proceeds in the following sequence:
CreateModel. This is called if the model has not yet been instantiated. The model must be created so that it can be provided as the argument to an action method.
OnModelUpdating. Override this method to perform preparation work on the model before its properties are enumerated and bound. Return false in order to cancel binding for the entire model.
GetModelProperties. This returns a collection of PropertyDescriptor instances that will be used to update the model. Override this if you need to return custom PropertyDescriptor instances, such as for Dynamic Data binding.
BindProperty. This is responsible for binding a single property of the model object. It is called in a loop, once for each property. Within the loop, the following methods are called:
OnPropertyValidating. This is called when a value has been retrieved for the property (using the binder that corresponds to the property type), but before the property setter has been called. Override this method to perform validation before the property setter is called. Return false to cancel binding for this particular property.
SetProperty. This is responsible for setting the property. Override this method to perform validation as the property is set, such as catching an exception from the property setter.
OnPropertyValidated. This is called after the property setter has been executed. Override this method to perform validation after the property setter has been called, such as to get an IDataErrorInfo object.
OnModelUpdated. Override this to perform overall validation of the model after all properties have been set, but before the model is returned to the user.
Additionally, model binder attributes can now be placed on an interface. We also made the ModelStateDictionary class serializable to make Post/Redirect/Get (PRG) scenarios easier to implement.
Model Binder Support Added for IDataErrorInfo
The default model binder (DefaultModelBinder) now has support for model classes that implement the IDataErrorInfo interface. This provides a simple means of having a model object provide its own validation messages.
The following example shows a sample implementation of the IDataErrorInfo interface.
public class Product : IDataErrorInfo {
Dictionary _errors = new Dictionary();
public double UnitPrice {
get {
return _unitPrice;
}
set {
if (value >= 0.00) {
_unitPrice = value;
}
_errors.Add("UnitPrice", value + " is not valid. The unit price must be larger than 0.00.");
}
}
double _unitPrice;
public string Error {
get {
if (_errors.Count == 0) {
return null;
}
return "There were some errors in creating this product.";
}
}
public string this[string columnName] {
get {
string error;
if (_errors.TryGetValue(columnName, out error)) {
return error;
}
return null;
}
}
}
A view that uses this class might include markup such as the following:
<% using (Html.BeginForm()) { %>
Unit Price: <%= Html.TextBox("UnitPrice") %> <%= Html.ValidationMessage("UnitPrice") %>
<% } %>
A controller action method to display the view might look like the following example:
public ActionResult Index() {
Product p = new Product();
return View();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(Product product) {
if (ModelState.IsValid) {
return RedirectToAction("Index");
}
return View(product);
}
Suppose you enter a negative value in the text input and post it to the Index action. The default model binder checks to see whether your object implements IDataErrorInfo. If so, the binder uses that to determine whether there are further validation errors and what message to display for each error. For more information, see HYPERLINK "http://msdn.microsoft.com/en-us/library/system.componentmodel.idataerrorinfo.aspx" IDataErrorInfo Interface in the .NET Framework Class Library on the MSDN Web site.
Descriptor Types Added
The framework now includes several descriptor types (ControllerDescriptor, ActionDescriptor, ParameterDescriptor) that resemble types in the System.Reflection namespace, such as Type, MethodInfo, and ParameterInfo, but that are specific to ASP.NET MVC. The descriptor types are used in several locations in the framework, such as in the invoker and in action filters. These types can be queried for information about the current request or about the current action.
HtmlHelper Class Added
The Html property of ViewPage, ViewUserControl, and ViewMasterPage was changed to the HtmlHelper type.
New JavaScriptResult Action Result and JavaScript Controller Method Added
The JavaScriptResult class is used to execute JavaScript code that is created on the server and sent to the client. For example, when you use the built-in AJAX helpers to make a request to an action method, the method might return some JavaScript code that is immediately executed when it gets to the client, as shown in the following example:
public ActionResult DoSomething() {
script s = "$('#some-div').html('Updated!');";
return JavaScript(s);
}
This action method might be called by code such as the following:
<%= Ajax.ActionLink("click", "DoSomething", new AjaxOptions()) %>
(The example assumes that you have referenced the AJAX and jQuery libraries.)
Bug Fixes Since Beta
The following changes have been made since the Beta release in order to fix bugs.
DropDownList and ListBox helpers now use ViewData.Eval (instead of the dictionary indexer) to get values, which is consistent with the other helpers.
Html.BeginForm and Ajax.BeginForm have been fixed to not render a fully qualified URL.
Authorization filters now run before action-method parameter binding.
DropDownList now works with validation helpers. If you are using an override that allows a blank value to be selected but the list is associated with a required property, the model binders now report an error if no item in the drop-down list is selected.
When you are working with a group of radio buttons (by using the RadioButton helper method) with the same form field name, form posts now retain the correctly selected radio button.
Html.CheckBox no longer renders whitespace between the check box and the hidden input element. Also, it no longer renders HTML attributes on the hidden input element that are used to indicate the existence of the check box.
When a form posts to an action method that has a parameter name that matches a route parameter, the form value now overrides the route parameter. This fixes an issue in which a form that attempted to post a form field named id would not work because the default route has an id parameter.
The RenderPartial method no longer resets the content type of the response to text/html.
The Password method no longer renders the value attribute unless explicitly specified. It no longer reads the ModelState object.
ASP.NET MVC AJAX helpers were fixed so that the IsMvcAjaxRequest extension method now recognizes PUT and DELETE requests made from the ASP.NET MVC AJAX helpers.
An issue was fixed with trace output and output caching in which an exception would get thrown.
An issue was fixed with the default model binder, which would throw a StackOverflowException in some situations. This fix required changes to the model binder API, as described earlier.
A bug was fixed in which the DropDownList and ListBox methods would not read a selected value from ModelState.
An issue was fixed in which partial views were not correctly located in a fully compiled, non-updatable site.
The AuthorizeCore method was updated in the AuthorizeAttribute class to accept an HttpContextBase object instead of an IPrincipal object.
The Html.ValidationMessage method no longer throws an exception when passed an empty string. Passing in an empty string is valid. Passing in null still throws an exception.
The ModelState.IsValidField method performs a key prefix match instead of an exact key match.
An issue was fixed in which the Html.ValidationMessage and Html.ValidationSummary properties displayed exception messages. They now display a generic message that you can override.
The default Visual Basic template now compiles when Option Strict is enabled.
The HandleErrorAttribute class now shows the correct error view in IIS. This filter does not run when custom errors are off and when the application is running in localhost debug mode.
The AddModelError class now accepts an empty string as an error message.
Upgrading from the Beta Release to the Release Candidate
There are not many changes between the Beta and the RC releases. However, you will need to make a few changes to your applications after installing the Beta release. Most of these changes are apparent when you try to compile your application by using the latest release, so we do not list every possible change.
The following list describes some of the changes that you must make.
Update the references to the following assemblies to point to the RC versions:
System.Web.Abstractions.dll
System.Web.Routing.dll
System.Web.Mvc.dll
NoteIf you are running ASP.NET 3.5 SP1, you need to update only the System.Web.Mvc assembly reference.
By default, these assemblies are located in the following folder:
%ProgramFiles%\Microsoft ASP.NET\ASP.NET MVC RC
After you have made these changes, compile your application and resolve any compilation errors. Most of the errors will be the result of one of the breaking changes listed earlier.
Update the section the Web.config file In the Views folder to match the following example. (The changed elements are in bold.)
Known Issue with the RC
There is a known issue with code nuggets within the head section of the page when the section does not contain a title tag as it does with the default Site.master file. The following code will throw an exception:
<%= GenerateMetaTag() %>
This is the exception that this code throws.
The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).
The simple workaround is to add PlaceHolder control around the code nugget.
<%= GenerateMetaTag() %>
Known Installer Issues
The following sections contain descriptions and possible solutions for known issues that may cause the installer to fail.
Conflict with Visual Studio Add-Ins
Certain Visual Studio add-ins can cause the installer to fail. The following add-ins are known to cause problems when installing ASP.NET MVC:
PowerCommands
Clone Detective
The final steps of the installation process install and configure the MVC templates in Visual Studio. When the installer encounters a problem during these steps, the installation will be stopped and rolled back.
You can produce a log file for the MVC installation process by using the msiexec command at the command prompt, using the following syntax:
msiexec /i AspNetMVCRC-setup.msi /q /l*v mvc.log
If an error occurs, the log file will contain an error message similar to the following example:
MSI (s) (C4:40) [20:45:32:977]: Note: 1: 1722 2: VisualStudio_VSSetup_Command 3: C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe 4: /setup
MSI (s) (C4:40) [20:45:32:979]: Product: Microsoft ASP.NET MVC Beta -- Error 1722. There is a problem with this Windows Installer package. A program run as part of the setup did not finish as expected. Contact your support personnel or package vendor. Action VisualStudio_VSSetup_Command, location: C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe, command: /setup
Error 1722. There is a problem with this Windows Installer package. A program run as part of the setup did not finish as expected. Contact your support personnel or package vendor. Action VisualStudio_VSSetup_Command, location: C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\devenv.exe, command: /setup
This error is usually accompanied by a corresponding event such as the following, which will be logged in the Windows Event Viewer:
Faulting application devenv.exe, version 9.0.30729.1, time stamp 0x488f2b50, faulting module unknown, version 0.0.0.0, time stamp 0x00000000, exception code 0xc0000005, fault offset 0x006c0061, process id 0x10e0, application start time 0x01c9355ee383bf70
In most cases, removing the problematic add-ins before installing MVC will resolve the problem.
Cryptographic Services
In a few isolated cases, the Windows Event Viewer might contain an Error event with event source CAPI2 and event ID 513. The event message will contain the following text:
Cryptograhpic Services failed while processing the OnIdentity() call in the System Writer Object.
The article HYPERLINK "http://technet.microsoft.com/en-us/library/cc734021.aspx"Event ID 513 Shadow Copy System Writer Functionality on the Microsoft TechNet Web site describes steps that you user can take to correct the problem. In some cases, simply stopping and restarting the cryptographic services allows the installation to proceed.
Visual Studio Templates
During the installation process, the installer creates a log file while configuring the MVC project templates in Visual Studio. The log file can be found at the following location:
%temp%\MvcTemplates.Log
If the installer fails, or if it completes but the MVC templates are not available in Visual Studio, the log file might contain additional information about problems that were encountered during this part of the installation.
ASP.NET MVC RC Release Notes Page PAGE 1
Copyright 2009 Microsoft Corporation
= L n x | } $ % & ' 1 2 3 M 䶯odUd j h