views:

53

answers:

0

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; }
}