Complex ModelBinders and being in charge of creating part of the model
Posted
by Kieron
on Stack Overflow
See other posts from Stack Overflow
or by Kieron
Published on 2010-04-15T18:59:22Z
Indexed on
2010/04/15
19:03 UTC
Read the original article
Hit count: 605
asp.net-mvc-2
|modelbinders
Hi,
I've a scenario where I need to bind to an interface - in order to create the correct type, I've got a custom model binder that knows how to create the correct concrete type (which can differ).
However, the type created never has the fields correctly filled in. I know I'm missing something blindingly simple here, but can anyone tell me why or at least what I need to do for the model binder to carry on it's work and bind the properties?
public class ProductModelBinder : DefaultModelBinder
{
override public object BindModel (ControllerContext controllerContext, ModelBindingContext bindingContext)
{
if (bindingContext.ModelType == typeof (IProduct))
{
var content = GetProduct (bindingContext);
return content;
}
var result = base.BindModel (controllerContext, bindingContext);
return result;
}
IProduct GetProduct (ModelBindingContext bindingContext)
{
var idProvider = bindingContext.ValueProvider.GetValue ("Id");
var id = (Guid)idProvider.ConvertTo (typeof (Guid));
var repository = RepositoryFactory.GetRepository<IProductRepository> ();
var product = repository.Get (id);
return product;
}
}
The Model in my case is a complex type that has an IProduct property, and it's those values I need filled in.
Model:
[ProductBinder]
public class Edit : IProductModel
{
public Guid Id { get; set; }
public byte[] Version { get; set; }
public IProduct Product { get; set; }
}
© Stack Overflow or respective owner