Casting objects coming back from Ajax

110 Views Asked by At

I'm using AJAX.NET and C# ASP.NET

My Soldier class is a type of Person class.

 [WebMethod, ScriptMethod]
 public static Person getPerson(int personId)
 {
    return (Person)personService.getSoldier(personId);
 }

This works perfectly well. On the Ajax side, I can get and set the Soldier properties. However, when I send this object back, I can't convert it back to a Soldier object.

[WebMethod, ScriptMethod]
public static Person savePerson(Person person)
{
   Soldier soldier = (Soldier)person;
}

This fails. It says it can't convert object Person to Soldier. Is there a way around this because I don't want to create a dozen of save methods for every type? Any help from you would be greatly appreciated.

3

There are 3 best solutions below

0
Parv Sharma On

what you can do is that.

Soldier soldier = new Soldier(){soldier.Prop1 = Person.CorrespondingProp;//for all the propertiese};
2
Mathew Thompson On

"My Soldier class is a type of Person class"

That's your problem right there. As Person is the base class, it cannot be cast to the child class Soldier.

You'll need to write a Convert function in your Person class that takes a Soldier as a parameter and set the properties individually.

2
Shyju On

I guess you created the Soldier Class from Person class. Your methods return type is Person class that is the base class. A base class will not have all the attributes of the Child class. But a child class will have all attributes of its Parents.

Ideally, i you are returning a Soldier object, i would make my method return type as Soldier

 public static Soldier getPerson(int personId)
 {
    return personService.getSoldier(personId);
 }