Our ProductsController's "Create" Action method is
responsible for handling the form posting of our "Add Product"
scenario. It currently handles incoming form parameters as
arguments to the action method:
This approach works fine - although for forms
involving large amounts of values the method signatures on Actions can start to
become a little hard to read. The code above that sets all of the
incoming parameter values to the new Product object is also a little long and monotonous.
If you reference the MVCToolkit assembly, you
can optionally take advantage of a useful Extension Method implemented within
the System.Web.Mvc.BindingHelpers namespace that can help clean this up a
little. It is called "UpdateFrom" and can be used on any .NET
object. It takes a dictionary of values as an argument, and it will then
automatically perform a property assignment on itself for any key that matches
a public property on the object.
For example, we could re-write our Create
action method above to use the UpdateFrom method like so:
Note: if you want to be more explicit for security reasons
and only allow certain properties to be updated, you can also optionally pass a
string array of the property names to update to the UpdateFrom method: