使用浮点数时,ASP.NET MVC ViewModel绑定的十进制为空 [英] ASP.NET MVC ViewModel binded decimal empty when using floating point numbers

查看:88
本文介绍了使用浮点数时,ASP.NET MVC ViewModel绑定的十进制为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个ViewModel对象,该对象的十进制字段包含价格.当我将其发布到我的控制器时,会发生以下情况:

I created a ViewModel object that has a decimal field containing a price. When I post that to my controller, this is what happens:

  • 输入"15"->确定!控制器收到15.
  • 输入"15.00"->不好!控制器收到一个空"字段.
  • 输入"15,00"->验证错误,因为该字段应使用句点格式设置(我只是坚持使用一种格式设置类型,以免暂时避免复杂化).
  • 输入"15.00M"->验证错误,可能是因为它不被认为是数字.

我该如何解决?我希望"15.00"是一个正确的值,但是我不知道该怎么做.我尝试了一些在Interweb上找到的自定义模型绑定器,但是它们没有用.

How do I fix this? I want "15.00" to be a correct value, but I can't figure out how to do this. I tried a couple of custom modelbinders that I found on the interweb, but they didn't work.

推荐答案

最简单的解决方法是将语言固定在web.config文件中:

Easiest way to fix this is to pin the language in the web.config file:

<globalization culture="en-us" uiCulture="en-us" />

您必须将其放置在<system.web>节点中.

you have to place this one in the <system.web> node.

为什么最简单?这样,包含的JavaScript助手就可以毫无问题地进行验证(通过假设数字应为美国格式的值来完成),现在(由于我们的更改)服务器上的相同.因此,在客户端有效的内容在服务器端也有效(该声明仅对简单情况和启用JavaScript的浏览器有效).

Why is it the easiest? This way the included JavaScript helpers can do validation without problems (which is done by assuming that numbers should be US formatted values), which is now (due to our changes) the same on the server. Therefore something that is valid on the client side will also be valid on the server side (statement only valid for simple cases and JavaScript enabled browsers).

所有其他选项都涉及更多的编辑,扩展和有关MVC 3中本地化的知识.

All other options involve more editing, extending and knowledge about localization in MVC 3.

这篇关于使用浮点数时,ASP.NET MVC ViewModel绑定的十进制为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆