dynamic model and ModelState
-
12-11-2019 - |
문제
I have an Action like this:
Update([Bind(Prefix = "CurrentModel")] dynamic edited)
but when I use dynamic the ModelState.IsValid
always returns true so it seems like there is no validation on the dynamic object? If not, how can I solve this?
해결책
There are two cases:
You are using view models as action arguments in which case the default model binder automatically assigns the properties and sets possible errors to the model state:
public ActionResult Update([Bind(Prefix = "CurrentModel")] EditViewModel edited) { if (ModelState.IsValid) { } ... }
You are using some weak typing with either
dynamic
orFormCollection
in which case the default model binder doesn't kick in and doesn't perform any validation at all as it is not capable of infering your real model type. In this case you need to manually callTryUpdateModel
and indicate your model type:public ActionResult Update(dynamic edited) { var model = new MyViewModel(); if (!TryUpdateModel(model, "CurrentModel")) { // The model was not valid } ... }
Conclusion: using dynamic
as action argument in a controller action makes very little sense.