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。为什么是这样?

4

2 回答 2

1

我认为呼叫return base.CreateModel很好,正如您所尝试的那样。

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

bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, typeToInstantiate);
于 2014-01-24T20:37:28.383 回答
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;
    }
}
于 2013-08-03T20:34:20.537 回答