Tuesday, August 23, 2011

Automagically new up an object upon model binding!

public class FooModel

{

   public Foo Foo { get; set; }

   public string SomethingElse { get; set; }

   public string SomethingMore { get; set; }

   
more code follows...

 
 

What if you have a view model that wraps a domain object such as in the case above wherein a Foo is one of many get-setters on FooModel? And, what if you bind to the model after posting a form as given here?

[HttpPost]

public ActionResult Create(FooModel fooModel)

{

   
more code follows...

 
 

Let's say you have a form field named SomethingElse, but not one named SomethingMore. Well, then it stands to reason that (when you submit the form) the controller action shown above will bind a value to SomethingElse and that fooModel will end up with that value for SomethingElse while having a null value for SomethingMore. As SomethingMore has a null value, it is pretty safe to bet that Foo has a null value too as certainly a form is not going to have a field to correspond to a complex, custom type. There is no reason to believe that an instance of an object will be instantiated for Foo. However, what if we took this line in our view...

@Html.EditorFor(model => model.SomethingElse)

 
 

...and made it this line...

@Html.EditorFor(model => model.Foo.SomePropertyOnFoo)

 
 

Now when the form posts it maps user-driven content to a get-setter on Foo which is in turn a get-setter on FooModel. A Foo will be "newed up" in this process. Why does this matter? It has bearing as to whether you need to new up Foo before casting properties to it from other parts of FooModel in advance of saving Foo. I ran into a pain point today wherein I replaced something like the line above with something like the line just above it. In this scenario, where Foo had always been instantiated in my Action (and I could assign stuff to its get-setters), it ceased to be (and code blew up at the point of first assignment). It was a little tricky to understand what was lacking since I had no memory of newing up a Foo to begin with given that it was happening for me behind the scenes.


Ta-Da! It's magic!

No comments:

Post a Comment