2

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

1 回答 1

0

ModelBinder 以递归方式工作,因此您需要做的是实现自定义模型绑定器,在其中覆盖方法 onCreate 和 BindModel。

protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
{
// get actual type of a model you want to create here
    return Activator.CreateInstance(type);
}

public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
    // here our CreateModel method will be called
    var model = base.BindModel(controllerContext, bindingContext);
    // we will get actual metadata for type we created in the previous line
    var metadataForItem = ModelMetadataProviders.Current.GetMetadataForType(() => model, model.GetType());
    // and then we need to create another binding context and start model binding once again for created object
    var newModelBindingContext = new ModelBindingContext
        {
            ModelName = bindingContext.ModelName,
            ModelMetadata = metadataForItem,
            ModelState = bindingContext.ModelState,
            PropertyFilter = bindingContext.PropertyFilter,
            ValueProvider = bindingContext.ValueProvider
        };
        return base.BindModel(controllerContext, newModelBindingContext);

}

希望有帮助。

于 2012-04-26T04:02:52.600 回答