问题
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