ASP.NET MVC:从空白字符串绑定数字类型而不会出现 ModelState 错误
我有一个相当复杂的 ViewModel,其中包含十进制属性,这些属性以文本框的形式向用户公开。 我想要一个没有值的文本框被解释为零。 (底层域对象中的属性不可为空,默认值为 0。)
当 DefaultModelBinder
将视图数据绑定到 ViewModel 时,输入为空字符串的十进制属性将初始化为零(按照 .NET 中的标准),但是 DefaultModelBinder
正在向空白文本框的 ModelState 添加错误。 因此,ModelState 无效,用户会看到一大堆“需要一个值”。 他们留空的文本框出现错误。
如何阻止这些错误添加到 ModelState 中?
I have a fairly complex ViewModel containing decimal
properties, which are exposed to the user in the form of text boxes. I want a textbox with no value to be interpreted as zero. (The properties in the underlying domain object are non-nullable, and the default value is 0.)
When the DefaultModelBinder
binds the view data to the ViewModel, decimal properties with blank strings for inputs are initialized to zero (as is standard in .NET), but the DefaultModelBinder
is adding errors to the ModelState for the blank text boxes. As a result the ModelState is invalid and the user sees a whole bunch of "A value is required." errors for the textboxes they left blank.
How can I stop these errors from being added to the ModelState?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在这种情况下,您可以做的最好的事情就是创建一个 ViewModel。 不要直接绑定到域模型,而是绑定到专门为了将数据传输到视图而创建的 ViewModel。 在 ViewModel 上,您可以将这些字段创建为可为空的小数。 然后,您可以根据需要将 ViewModel 映射回域模型。
这确实是正确的行为。 如果您在 TextBox 中未输入任何内容,则相当于 null,而不是 0。
The best thing that you could do in this situation is to create a ViewModel. Instead of binding directly to your Domain Model, instead bind to the ViewModel that was created solely for the purpose of Data Transfer to your view. On the ViewModel, you can create these fields as nullable decimals. You can then map the ViewModel back to your Domain Model however you like.
This is really the correct behavior. If you enter nothing in the TextBox then that is equivalent to null, not 0.