在ModelBinder中实例化一个子类型对象

时间:2017-12-07 20:27:53

标签: c# .net asp.net-mvc

我有一个基类,还有两个派生的类,这两个类的每个类都有两个派生类。我需要在我的modelBinder中根据子类型实例化我的对象实例化相应的类

在这里查看我的代码

public class Product
{
    public ProductType ProductType;//ProductA,ProductB
}

public class ProductA : Product
{
    public subType AsubType;// AsubType ProductAH et ProductAF
}

public class ProductB : Product
{
    public subType BsubType; // BsubType ProductBC et ProductBD
}


public class ProductAH : ProductA { }

public class ProductAF : ProductA { }

public class ProductBC : ProductB { }

public class ProductBD : ProductB { }



protected override object CreateModel(ControllerContext controllerContext, ModelBindingContext bindingContext, Type modelType)
{
    if (modelType.Equals(typeof(Product)))
    {               
        //instantiate a object ProductAH or ProductAF or BC or BD according to subtype

        Type instantiationType = typeof(xxxx);
        var obj = Activator.CreateInstance(instantiationType);
        bindingContext.ModelMetadata = ModelMetadataProviders.Current.GetMetadataForType(null, instantiationType);
        bindingContext.ModelMetadata.Model = obj;
        return obj;
    }
    else 
    {
        return base.CreateModel(controllerContext, bindingContext, modelType);
    }
}

1 个答案:

答案 0 :(得分:1)

我用这段代码解决了我的问题:

var keySubType = bindingContext.ModelName.ToString() + "."+"SubType";
string subtypeName = bindingContext.ValueProvider.GetValue(keySubType).AttemptedValue;

Type instantiationType = null;
switch (subtypeName)
{
    case "ProductAH":
        instantiationType = typeof(ProductAH );
        break;
    case "ProductAF":
        instantiationType = typeof(ProductAF );
        break;
    case "ProductBC":
        instantiationType = typeof(ProductBC );
        break;
    case "ProductBD":
        instantiationType = typeof(ProductBD );
        break;
}

//Create an instance of the specified type
var obj = Activator.CreateInstance(instantiationType);