How is Modelstate.IsValid triggered?
Hello!
I am reading this tutorial on how DTO's can be implemented with API's: https://dev.to/moe23/net-6-automapper-data-transfer-objects-dtos-49e
The process in this tutorial seems normal and you can easily follow along.
There are only 2 things I have my questions about:
1. The Driver class in this tutorial has no DataAnnotations (see first codeblock). How come the Modelstate.IsValid can be triggered in codeblock 2?
2. How does Modelstate.IsValid get triggered when a Dto is passed but it gets mapped to an entity?
DEV Community
.NET 6 - AutoMapper & Data Transfer Objects (DTOs) 🗺
Intro In this article we will be exploring AutoMapper and Data Transfer Objects (DTOs) in...
39 Replies
If it can't bind json to that object. Like if it can't parse a string as a datetime. Or if the json is invalid in some way too, I think. Like if you pass
tru
instead of true
.Would not the _mapper function then crash?
No the parameter will have the defaults for those properties then
But that cab only happen if you turn off the filter that shortcircuits this in MVC
generally, it would return a response automatically at that point
Or maybe it will just be null? not sure
the mapper has nothing to do with ModelState
I have a little hard time to understand this.
thats correct
well just try passing some garbage json with the default mvc settings
and see what error you get
it won't even get to your code
oh like that.
But it will ignore extra fields, I'm pretty sure
and if you don't provide a value for a property, it will initialize it to null
if we check the Driver model for example in the code above. Lets say the driver number should be between 1 and 5 and the DTO contains 0?
then it should fail
no it won't handle that automatically
unless you do data annotations
and enable them, I think they aren't on by default
yes data annotations should be added. But you should not add data annotations on DTO's
Well then you won't be using MVC's system for validation
which isn't good in the first place, to be fair
data annotations are pretty primitive
Since the DTO comes in at the controller. you would 'normally' validate the object that comes in.
well one thing for certain
i do say that adding basic validation, like required or min/max length would be OK.
mapping typically never does any validation