首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >ModelBinders、复杂嵌套类型和接口

ModelBinders、复杂嵌套类型和接口
EN

Stack Overflow用户
提问于 2010-04-16 02:59:23
回答 1查看 504关注 0票数 2

我有一个场景,我需要绑定到一个接口--为了创建正确的类型,我有一个自定义的模型绑定器,它知道如何创建正确的具体类型(可能有所不同)。

但是,创建的类型永远不会正确填充字段。我知道我在这里遗漏了一些非常简单的东西,但是谁能告诉我为什么,或者至少我需要做些什么才能让模型绑定器继续它的工作并绑定属性?

代码语言:javascript
复制
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;
    }
}

在我的例子中,模型是一个具有IProduct属性的复杂类型,它是我需要填充的那些值。

型号:

代码语言:javascript
复制
[ProductBinder]
public class Edit : IProductModel
{
    public Guid Id { get; set; }
    public byte[] Version { get; set; }

    public IProduct Product { get; set; }
}
EN

回答 1

Stack Overflow用户

发布于 2012-04-26 12:02:53

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

代码语言:javascript
复制
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);

}

希望这能有所帮助。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/2648160

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档