0

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?

Vandesh
  • 6,368
  • 1
  • 26
  • 38
  • There should be no problem passing "SuperClass". What's the actual issue? You need some client and server code and some indication about where you're encountering an issue. – Mick Sep 23 '14 at 00:10
  • I suspect the issue is in the JSON. I'd suggest going the other way first. Instantiate your derived objects, put them in your Superclass and serialize the SuperClass to JSON then make sure that the format of the JSON you're passing from your JScript matches what is generated from your data contracts – Mick Sep 23 '14 at 00:45
  • This might be helpful... http://stackoverflow.com/questions/6348215/how-to-deserialize-json-into-ienumerablebasetype-with-newtonsoft-json-net/6495299#6495299 – Mick Sep 23 '14 at 01:05
  • Thanks for the link @Mick , I'll sure give it a try. Also, I checked the JSON against the sample JSON request for that contract and it confirms with it. Would still be interested in behind-the-scenes understanding of this! – Vandesh Sep 23 '14 at 01:30
  • What happens when you try and deserialize the JSON created from Serializing SuperClass ? – Mick Sep 23 '14 at 05:45

0 Answers0