动态模型和ModelState
我有一个像这样的操作:
Update([Bind(Prefix = "CurrentModel")]dynamicedited)
但是当我使用动态时ModelState.IsValid
总是返回true,所以它似乎没有对动态对象进行验证?如果不是,我该如何解决这个问题?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有两种情况:
您使用视图模型作为操作参数,在这种情况下,默认模型绑定器会自动分配属性并将可能的错误设置为模型状态:
您正在使用一些弱类型与
动态
或FormCollection
在这种情况下,默认模型绑定器不会启动,并且根本不执行任何验证,因为它无法推断您的真实模型类型。在这种情况下,您需要手动调用TryUpdateModel
并指明您的模型类型:结论:在控制器操作中使用
dynamic
作为操作参数没有什么意义。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:
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:Conclusion: using
dynamic
as action argument in a controller action makes very little sense.