Mohammad Dayyan Mohammad Dayyan - 4 months ago 10
C# Question

Decimal symbol issue in MVC, C#?

I'm using MVC 5.0

I set the culture in config:

<system.web>
<globalization uiCulture="fa-IR" culture="fa-IR" />
</system.web>


I have a model as the following:

public class MyModel
{
[DisplayName("NbatPersent")]
[Range(0, 100)]
public double NbatPersent{ get; set; }
}


MVC shows the
NbatPersent
value in View like
22/5
and when I wanna submit form the form validator alert me
The field NbatPersent must be a number.
. It can't convert
22/5
to
22.5


It will be OK if I enter 22.5 but if the property has a value it convert
.
to
/


How can I convert all numeric properties' culture to
en-US
to show value like
22.5
not like
22/5
.

Edit:

I'm using
@Html.TextBoxFor
to show the decimal property because of user should be change it.

Answer

You are getting a client side validation error as a result of jquery.validate.js which uses the following to validate the value (which only allows the . character as the decimal separator.

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

You can use the jquery.validate.globalize.js plugin (refer this article for more detail) or you can add your own script to modify the validator, for example (include this after jquery.validate.js)

$.validator.methods.number = function (value, element) {
   return this.optional(element) || $.isNumeric($(element).val().replace('/', '.'));
}