Many times I need a model binder that will retrieve my model from a repository so that I can perform updates. Here’s what I came up with.
1: public class EntityRetrievalBinder<T, TRepository> : IModelBinder
2: where TRepository : IRepository<T>
3: {
4: #region IModelBinder Members
5:
6: public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
7: {
8: var name = bindingContext.ModelName + ".ID";
9: ValueProviderResult idResult;
10: try
11: {
12: if (bindingContext.ValueProvider.TryGetValue(name, out idResult))
13: {
14: Guid id = new Guid(idResult.AttemptedValue);
15: var repository = StructureMap.ObjectFactory.GetInstance<TRepository>();
16: T obj = repository.FindById(id);
17: if (obj == null)
18: throw new ArgumentException("Object not found");
19: return obj;
20: }
21: }
22: catch (Exception e)
23: {
24: }
25: return null;
26: }
I changed a couple things for this post, but basically the logic is simple. What this does is just retrieve the repository from StructureMap and then try to run the Find() method which takes a Guid ID as its only parameter. Either this will return a null (if no ID was posted) or an object of type T OR it might throw an exception if the user posted an ID but that ID was not found. I’ll show you in the next post how I tie everything together.