I have a class with a constructor as follows
public SomeClass
{
List<string> MyList;
public SomeClass()
{
this.MyList = new List<string>() { "1","2","3" };
}
}
my ajax post is as follows:
{MyList:["a","b","c"]}
in the conroller I have
public void Post([FromBody]Models.SomeClass example)
{
Debug.WriteLine(example.MyList);
}
the output is:
["1","2","3","a","b","c"]
I expected:
["a","b","c"]
I expect exactly what was posted rather than the initial values with the posted values appended. Not sure what's going on here, why is the initial state of the list not being overwritten?
I ran into that same behavior a couple months back. I concluded what was happening was, as the WebAPI service received a POST request with some data, it would:
I know, you can probably infer that from the result, and you illustrated that nicely.
But what I ended up doing is moving out any initial value-setting from the type constructor into a Factory, for situations when I'd need those "default" values set. Then when new() gets called as part of a POST, it returns an empty List, so the values added from the POST are the only values that end up in the object.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With