Noah Blumenthal's Blog

July 10, 2009

Retrieve OR Instantiate ModelBinder

Filed under: Uncategorized — noahblu @ 2:25 am

Sometimes you want your model binder to retrieve an object if it exists or instantiate it if it doesn’t.  For instance I have a create page and an edit page for my models so on the create page I want the model to be instantiated but I also have an edit page that posts back the ID of the model and I’d love the entity to be retrieved from the DB for further edits.  SO…..

I created a ModelBinder that actually takes two different model binders and tries to bind with each.  If it works the first time, great, otherwise try the backup.  In my case that’s Retrieval with a backup of Instantiate.  This could be used for many different purposes though, so don’t let the class name throw you off:

   1: public class RetrieveOrInstantiateModelBinder : IModelBinder

   2: {

   3:     private IModelBinder _retrievalBinder;

   4:     private IModelBinder _instantiationBinder;

   5:     public RetrieveOrInstantiateModelBinder(IModelBinder retrievalBinder, IModelBinder instantiationBinder)

   6:     {

   7:         _retrievalBinder = retrievalBinder;

   8:         _instantiationBinder = instantiationBinder;

   9:     }

  10:     #region IModelBinder Members

  11:  

  12:     public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)

  13:     {

  14:         object obj = _retrievalBinder.BindModel(controllerContext, bindingContext);

  15:         if (obj == null)

  16:             obj = _instantiationBinder.BindModel(controllerContext, bindingContext);

  17:  

  18:         return obj;

  19:     }

  20:  

  21:     #endregion

  22: }

Advertisements

Leave a Comment »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Blog at WordPress.com.

%d bloggers like this: