0

My project is based on .Net framework 4.6.2. I have a controller that takes a parameter, that is an array of objects. And inside object there is nested object.

My frontend payload looks like this:

const customerList = [
  {
    Name: 'John',
    Pets: {
      Cat: false,
      Dog: false,
      Bird: false,
      Mouse: true,
    },
  },
  {
    Name: 'Mary',
    Pets: {
      Cat: false,
      Dog: false,
      Bird: false,
      Mouse: true,
    },
  },
];

const data = {
  customerList,
};

const res = await fetch(url, {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(data),
});

My backend code can loop through my customerList, and it can read the value from Name like 'John', but it can't read the correct value in the nested object "Pets", it just show all false values like this:

Pets: {
  Cat: false,
  Dog: false,
  Bird: false,
  Mouse: false,
},

My backend model looks like this:

    public class Customer
    {
        public string Name { get; set; }
        public Pets Pets{ get; set; }
    }

    public class Pets
    {
        public bool Cat;
        public bool Dog;
        public bool Bird;
        public bool Mouse;
       
    }
    

and when I trying to access the pets property...

     foreach (var customerInfo in customerList)
     {
       var name = customerInfo.Name; // shows correct value 'John'
       var pets = customerInfo.Pets; // did not show the correct value, all false
    }

I googled many times but can't find a example like me, I wonder is my keyword not specific or not. Is there anything I am missing? Many thanks!!

Doraemon
  • 439
  • 1
  • 6
  • 17

1 Answers1

1

The default model binder requires properties with public getter/setter.

If you change your fields in Pets class to properties, it will work.

public class Pets
{
    public bool Cat { get; set; }
    public bool Dog { get; set; }
    public bool Bird { get; set; }
    public bool Mouse { get; set; }
}

Otherwise, you could also implement your own model binder, if you want to keep them as fields. Maybe this question will help you

johnmoarr
  • 430
  • 3
  • 7