MVC3 edit for decimal fields and localization

2019-02-06 15:35发布

问题:

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);
}