The RC build includes a number of form-post specific
enhancements:
[Bind(Prefix=””)] No Longer Required for Common Scenarios
The RC build no longer requires you to explicitly use a
[Bind] attribute (or set its prefix value to “”) in order to map incoming form
post parameters that do not have a prefix to complex action method parameters.
To see what this means, let’s implement the “Create”
scenario for our ProductsController. We’ll begin by implementing the
HTTP-GET version of our “Create” action method. We’ll do this with code
below that returns a View based on an empty Product object:
Figure 28
We can then right-click within our action method, choose the
“Add View” command and scaffold a “create” view template that is based on a
Product:
Figure 29
Notice above how our Html.TextBox() helper
methods are referencing the “ProductName” and “SupplierID” properties on our
Product object. This will generate HTML markup like below where the input
“name” attributes are “ProductName” and “SupplierID”:
Figure 30
We can then implement the HTTP-POST version of
our “Create” action method. We’ll have our action method take a Product object
as a method parameter:
Figure 31
With the ASP.NET MVC Beta we would have had to
add a [Bind(Prefix=””)] attribute in front of our Product argument above – otherwise
the ASP.NET MVC binding infrastructure would have only looked for form post
values with a “productToCreate.” prefix (for example:
productToCreate.ProductName and productToCreate.SupplierID) and not found the
submitted values from our form (which don’t have a prefix).
With the RC build, the default action method
binders still first attempt to map a productToCreate.ProductName form value to
the Product object. If they don’t find such a value, though, they now
also attempt to map “ProductName” to the Product object. This makes
scenarios where you pass in complex objects to an action method syntactically
cleaner and less verbose. You can take advantage of this feature both
when mapping domain objects (like our Product object above) as well as with Presentation
Model/ViewModel classes (like a ProductViewModel class).
A completed implementation of our Create
action method (including basic input type error handling) might look like
below:
Figure 32
Now our create action will save the Product object if all
values are entered correctly. When a user attempts to create a Product
with invalid Product property values (for example: a string “Bogus” instead of
a valid Decimal value), the form will redisplay and flag the invalid input
elements in red:
Figure 33