MVC3 edit for decimal fields and localization

我怕爱的太早我们不能终老 提交于 2020-01-10 14:16:34

问题


My locale uses a comma ,, and not a dot . for decimal separator.

In MVC3, when I open an Edit view where the decimal values are shown with

@Html.EditorFor(model => model.MyDecimalVal)

the value is shown correctly.

When I enter value with comma, I get error "Value is not a number" and if I enter value with dot, I get no error, but actually no value is saved.

How to handle this situation?


回答1:


Getting around with this by tweaking your validation logic has been already explained so here is a different approach.

Put the below code inside your web.config file under the <system.web> node if you would like to set the culture to en. It will take care of decimal delimiter:

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

I am not sure but for DateTime, you are still bound to your server's locale.




回答2:


This blog post recommends overriding the default jQuery validate number and range rules in order to enable client-side support of the comma decimal separator.

To fix these problems, we can take the default implementation from the jquery.validate.js file for the range() and number() functions. We then create another .js file (say jQueryFixes.js), in which we override these default functions with ones that contain support for the comma as a decimal separator. The contents of the file should be something like this:

$.validator.methods.range = function (value, element, param) {
    var globalizedValue = value.replace(",", ".");
    return this.optional(element) || (globalizedValue >= param[0] && globalizedValue <= param[1]);
}

$.validator.methods.number = function (value, element) {
    return this.optional(element) || /^-?(?:\d+|\d{1,3}(?:[\s\.,]\d{3})+)(?:[\.,]\d+)?$/.test(value);
}


来源:https://stackoverflow.com/questions/8101589/mvc3-edit-for-decimal-fields-and-localization

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