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

instantiate a sub-type object in ModelBinder

user1425 Published in March 24, 2018, 12:44 am

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;
        return base.CreateModel(controllerContext, bindingContext, modelType);
You need to login account before you can post.

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

© 2016 Powered by mzan.com design MATCHINFO