ASP.NET MVC Framework (Part 4): Handling Form Edit and Post Scenarios
page 9 of 15
by Scott Guthrie
Feedback
Average Rating: This article has not yet been rated.
Views (Total / Last 10 Days): 3769/ 166

Implementing Add New Product (Part 4 - Cleaning Up Create with the UpdateFrom Method)

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:

Figure 28

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:

Figure 29

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:

Figure 30


View Entire Article

Article Feedback

Title:  
Name:  
Url: ( Optional )
Comment:  
Please add 1 and 8 and type the answer here:

User Comments

No comments posted yet.






Ads Powered by Lake Quincy Media
Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2008 ASPAlliance.com  |  Page Processed at 7/4/2008 10:36:47 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search