0

I'm creating a .Net Core 3.1 Web Api Project where i have the following codes.

class Person{
    string name;
    int age;
}

class Student: Person{
    string grade;
}

class Teacher: Person{
    List<string> courses;
}

[HttpPost] 
savePersonList([FromBody] List<Person> personList){
    // Do something with the personList;
}

I call the api savePersonList and pass a list of students and teachers to it. However in the backend the personlist only give me Person object, the properties of Teacher and Student are not there.

What do i have to do to get the full properties of the list. The solution to this problem should be generalized because i have other controllers which got other type of objects.

Thanks.

AngularChan
  • 135
  • 2
  • 11
  • 2
    Serialization only uses the exact types you declare by default for security reasons. You can't generally use polymorphism with serialization in this way. More information can be found in this question: https://stackoverflow.com/q/45676566/1064169 – Martin Costello Oct 02 '20 at 11:32
  • also you as say they all person `List personList`, you cant then afterwords say there something else. – Seabizkit Oct 05 '20 at 05:53

1 Answers1

1

You may misunderstand the model binding.You could pass base class then receive with derived class but you can't pass derived class then receive with base class.

For your scenario,you could create a view model then you could pass each object you want:

public class ViewModel : Person
{
    public string grade { get; set; }
    public List<string> courses { get; set; }
}

Controller:

[HttpPost]
public void Post([FromBody] List<ViewModel> personList)
{
     //do your stuff...
}

Result:

enter image description here

Rena
  • 30,832
  • 6
  • 37
  • 72
  • hmm. I want to have a list of person, who can be a student or a teacher. The person class will have other inheritances too. So the question is how can i pass the list from frontend to backend. The approach with the viewmodel as you state is not the solution. But thanks anyway. – AngularChan Oct 06 '20 at 11:43
  • `So the question is how can i pass the list from frontend to backend.` If you just want to get the whole data in backend,just using `object` or `dynamic` to recieve the data.And I am not sure what is your real requirement,to create a view model with all different inheritance properties,you could pass any object successfully,I think it is the convenient way. If you want to receive Person in your backend,it is impossible,because you could not pass inheritance and receive base class.You could only pass base class and receive inheritance. – Rena Oct 07 '20 at 07:32