Model validation is Not working for the derived classes. even though i have mentioned the known types

420 Views Asked by At

I am using asp.net core 2.2 and model validation for server side validation. Its working fine except for known types.

this is my class structure

    //Main Class

    [DataContract]    
    [KnownType(typeof(SubClass2))]    
    [KnownType(typeof(SubClass1))]    
    public partial class MainCass : Base    
    {     
    //properties comes here     
    }     

    //Sub Classes    

    [DataContract]     
    public partial class SubClass1 : MainCass    
    {    
    //properties comes here    
    }    

    [DataContract]    
    public partial class SubClass2 : MainCass    
    {    

    [DataMember]    
    [CustomRequired(ErrorMessageResourceType = typeof(ErrorMessages),  
    ErrorMessageResourceName = "FieldRequired", Caption = "name required")]    
    public string Name  {get; set; }   

    }    

//this is my request model
    [DataContract]    
    public partial class request:Base    
    {    
    [DataMember]    
    public List<MainCass> MainCassList  {get; set; }    
    }    

now the validation attribute of Name in SubClass2 is not getting called. From UI I am sending type Subclass2.

1

There are 1 best solutions below

3
On

The model binder does not support polymorphism. It creates the literal type(s) of the model and any related sub-models. Then, it attempts to bind the request body to these types. It will not infer derived types.

In other words, it sounds like you're sending instances of SubClass1 and SubClass2 as part of your MainClassList property. However, the model binder is going to create all of these as MainClass because that's the type that's defined. Any posted data specific to SubClass1 or SubClass2 will simply be discarded, and in the end, all you have is instances of MainClass. As such, of course no specific validation on SubClass1 or SubClass2 is being run, because you have no instances of SubClass1 or SubClass2.