Home instantiate a sub-type object in ModelBinder
Reply: 1

instantiate a sub-type object in ModelBinder

mus
1#
mus Published in 2017-12-07 20:27:52Z

I have a base class, and two other classes derived for it, and each class of these two classes has two derived classes. I need in my modelBinder to instantiate my object according to the subtype instantiate the corresponding class

see my code here

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);
    }
}
mus
2#
mus Reply to 2017-12-11 17:53:36Z

I resolved my problem with this code :

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);
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.304028 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO