Decimal symbol issue in MVC, C#?

2019-05-26 13:38发布

问题:

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.

回答1:

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('/', '.'));
}


回答2:

Try to set the view format explicitly

@Html.DisplayFor(x => string.Format("{0:0.00}", x.NbatPersent));

else you can write a custom editor template for the double type (~/Views/Shared/EditorTemplates/double.cshtml):

@model double?
@Html.TextBox("", Model.HasValue ? Model.Value.ToString("#,##0.000#") : "")

and then in your view:

@Html.EditorFor(x => x.NbatPersent)