ASP.NET MVC ViewModel binded decimal empty when using floating point numbers

老子叫甜甜 提交于 2019-12-11 03:14:36

问题


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

  • Enter "15" -> ok! Controller receives 15.
  • Enter "15.00" -> not ok! Controller receives a 'null' field.
  • Enter "15,00" -> validation error because the field should be formatted with a period (I just stick to one formatting type to avoid complexity for the time being).
  • Enter "15.00M" -> validation error, probably because it's not considered to be a number.

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.


回答1:


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

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

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

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).

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




回答2:


Create a field of type string not mapped, like the following

[NotMapped]
public string priceComputed {get;set}

then in your controller, you set value at right field

price = convert.todecimal(pricecomputed)


来源:https://stackoverflow.com/questions/10657795/asp-net-mvc-viewmodel-binded-decimal-empty-when-using-floating-point-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!