On My Server side, I have the following structure -
[DataContract]
[KnownType(typeof(Derived1))]
[KnownType(typeof(Derived2))]
public class Base
{
}
[DataContract]
public class Derived1 : Base
{
[DataMember]
public string Prop1 {get;set;}
[DataMember]
public string Prop2 {get;set;}
}
[DataContract]
public class Derived2 : Base
{
[DataMember]
public string Prop3 {get;set;}
[DataMember]
public string Prop4 {get;set;}
[DataMember]
public string Prop5 {get;set;}
}
[DataContract]
public class SuperClass
{
[DataMember]
public List<Base> ListBase;
}
[OperationContract(Method="POST")]
public void SomeName(SuperClass superObj);
On the client side, I make an AJAX call to an Operation Contract which takes in SuperClass
object as parameter.
var dataObj = { ListBase : [{"Prop1":"This is","Prop2":"First Derived Class"},
{"Prop3":"This is","Prop4":"Second","Prop5":"Derived Class"}
]
};
$.ajax({
url : 'MyProperlyConstructedServiceUrlAsSpecifiedInTheOperationContract'
data : JSON.stringify(dataObj),
method : "POST",
contentType:'application/json'
});
Now, while constructing my JSON object on the client side, I pass the objects of both Derived1
and Derived2
in the List<Base>
.
The error I get is "Unable to Cast object of Type Base to object of Type Derived1".
Is there a way in which the OperationContract on the server side can 'know' which of the Derived object to cast into? Is it even possible? (Seems illogical to me, but I'm unable to fully understand the underlying concept...too much reading got me confused!)
What should be the design approach in such situations? Any example or any concept I should read about specifically for this situation?