自定义多态模型绑定程序不绑定派生类型的属性

时间:2013-08-03 19:18:11

标签: asp.net-mvc-4

这是我的自定义模型绑定器,用于实例化派生类。

public class LocationModalBinder : DefaultModelBinder
{
    protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext,
        Type modelType)
    {
        var type = bindingContext.ModelName + "." + "type";

        Type typeToInstantiate;

        switch ((string) bindingContext.ValueProvider.GetValue(type).RawValue)
        {
            case "store":
            {
                typeToInstantiate = typeof (Store);
                break;
            }
            case "billing":
            {
                typeToInstantiate = typeof(LocationReference);
                break;
            }
            case "alternate":
            {
                typeToInstantiate = typeof(Address);
                break;
            }
            default:
            {
                throw new Exception("Unknown location identifier.");
            }
        }

        return base.CreateModel(controllerContext, bindingContext, typeToInstantiate);
    }
}

问题是它不绑定子类型的属性。仅限基本类型Location上的属性。这是为什么?

2 个答案:

答案 0 :(得分:1)

我认为调用return base.CreateModel可以正常尝试。

我通过在return base.CreateModel行之前添加以下内容来解决它:

bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeToInstantiate);

答案 1 :(得分:0)

从这里做到了...... https://stackoverflow.com/a/9428558/221683

我不明白这种模型活页夹的例子有多少没有这些作业。

public class LocationModalBinder : DefaultModelBinder
{
    protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext,
        Type modelType)
    {
        var type = bindingContext.ModelName + "." + "type";

        Type typeToInstantiate;

        switch ((string) bindingContext.ValueProvider.GetValue(type).RawValue)
        {
            case "store":
            {
                typeToInstantiate = typeof (Store);
                break;
            }
            case "billing":
            {
                typeToInstantiate = typeof(LocationReference);
                break;
            }
            case "alternate":
            {
                typeToInstantiate = typeof(Address);
                break;
            }
            default:
            {
                throw new Exception("Unknown location identifier.");
            }
        }

        var model = Activator.CreateInstance(typeToInstantiate);

        bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeToInstantiate);
        bindingContext.ModelMetadata.Model = model;

        return model;
    }
}