Getting ASP.NET MVC to do the dirty work
Hey, whaddaya know! I have some actual feedback to give on something in the form of "boy, I wish the product could do X". Who knew I had evaluation skillz?
The product is ASP.NET MVC and I'm implementing some pretty standard functionality: Get the data from the user and save it in the database. For this post, we'll call the object being saved a Critter.
One of the properties on a Critter is Species and its value is selected from a dropdown list. This is not such a far cry from Scott Guthrie's equally descriptive Product/Category example which is an okay example if you're looking only for education and not entertainment.
Like Scott's version, I'm passing what amounts to a DTO as the ViewData. The DTO includes a list of Species to select from as well as the actual Critter object. You fill in the name of the critter, select your species, and click Save and watch the magic happen in the form of saving the Critter to the database.
Now, according to the tutorial, there are two ways to create your Critter object in the Create action. The first way is to specify a method parameter for each property. For example:
[ControllerAction] public void Create( string CritterName, int SpeciesID ) { Critter critter = new Critter( ); critter.Name = CritterName; critter.SpeciesID = SpeciesID; // Do "stuff" with the critter }
The second way is shorter and possibly cleaner:
[ControllerAction] public void Create( ) { Critter critter = new Critter( ); critter.UpdateFrom( Request.Form ); // Do "stuff" with the critter }
This one is kinda cool if a little too magic. Updating from a NameValueCollection sounds like it might be fragile but they seem to have a good collective head on their shoulders so that might not be a concern.
Here's where my wish list comes in. Neither of these methods are how I would code the thing if I were doing it in, say, a Windows app. Ideally, I'd like to be able to do this:
[ControllerAction] public void Create( ICritter critter ) { // Do "stuff" with the critter }
That is, I'd like the framework to create my critter for me. It can do this for primitive types but not so much with objects. Admittedly, this is probably a tall order without getting back into a ViewState state of being but a hillbilly can dream, can't he?
Kyle the Utopian