Retrieve OR Instantiate ModelBinder
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
3: private IModelBinder _retrievalBinder;
4: private IModelBinder _instantiationBinder;
5: public RetrieveOrInstantiateModelBinder(IModelBinder retrievalBinder, IModelBinder instantiationBinder)
7: _retrievalBinder = retrievalBinder;
8: _instantiationBinder = instantiationBinder;
10: #region IModelBinder Members
12: public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
14: object obj = _retrievalBinder.BindModel(controllerContext, bindingContext);
15: if (obj == null)
16: obj = _instantiationBinder.BindModel(controllerContext, bindingContext);
18: return obj;
No comments yet.