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.
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
andSubClass2
as part of yourMainClassList
property. However, the model binder is going to create all of these asMainClass
because that's the type that's defined. Any posted data specific toSubClass1
orSubClass2
will simply be discarded, and in the end, all you have is instances ofMainClass
. As such, of course no specific validation onSubClass1
orSubClass2
is being run, because you have no instances ofSubClass1
orSubClass2
.