Reputation: 39524
I have the following ASP.NET Core controller action:
public async Task<IActionResult> Post([FromBody]Model model) { }
The Model is the following:
public class Model {
public String Name { get; set; }
public Int32? Age { get; set; }
}
I then, using Angular, tried to post an invalid model:
model = { name: "John", age: "Ab }
On my controller the model becomes null. If I use age: 30
the model has the values defined.
If age has an invalid value shouldn't the model be defined and Age has the Int32? default value, e.g., null?
Upvotes: 0
Views: 793
Reputation: 3313
This is expected behaviour. The Int32? Age
accepts a null value but not an invalid value. The posted model with invalid age value tries to convert the value to an interger and this fails because the value is not an interger.
With the following json: { name: "John", age: "Ab }
the ModelState contains two errors:
Unterminated string. Expected delimiter: \
Unexpected end when deserializing object
Giving a correct string value { name: "John", age: "test"}
the ModelState contains one error:
Could not convert string to integer: test
Upvotes: 1