0

My model:

    [Required(ErrorMessage = "Required field")]
    [Display(Name = "Price")]
    public decimal Price { get; set; }

My view: There is a form with several other input fields and an input field for Price

@Html.EditorFor(model => model.Price, new { htmlAttributes = new { @class = "form-control"} })

Issue:

  • [Browser validation] If I insert 2.3 on input field I get "Field needs to be a number"
  • [Server Validation] If I insert 2,3 on input field it does not give any error immediately but after submitting the form I get "value not valid"

What I've tried: There is a lot of topics about this on SO so I've tried several suggestions but unfortunately without success.

  • Suggestion A - System.Globalization.CultureInfo.DefaultThreadCurrentCulture = new System.Globalization.CultureInfo("pt-PT"); in Application_Start()

  • Suggestion B - put <globalization uiCulture="pt-PT" culture="pt-PT" /> in web.config

  • Suggestion C - (in despair) data_val = "false" in input field to disable browser validation. When I did this I found two things: if I input 2.3 a value of 0 reaches the controller; if I input 2,3 a value of "2.3" (with the point) reaches the controller but after saved to the DB is loses the decimal part, I mean only "2" is saved on the DB table

  • Suggestion D - Even if I force a number with comma on the code, when I inspect it in debugging mode, I see it is using a dot and when stored in BD it only stores "2". How can that be possible?

    Ingredient ingredientToAdd = new Ingredient { Name = ingredient.Name, Price = Decimal.Parse("2,3"), VAT = ingredient.VAT };

        if (ModelState.IsValid)
        {
            db.Ingredients.Add(ingredientToAdd);
            db.SaveChanges();
            return RedirectToAction("Index");
        }
    
newhouse-pt
  • 141
  • 2
  • 13
  • You will not get a client side validation error if you enter 2.3 unless you have reconfigured the `$.validator` (not sure if that is a typo in your question, or you have omitted relevant information). I suggest you read [MVC/JQuery validation does not accept comma as decimal separator](https://stackoverflow.com/questions/48066208/mvc-jquery-validation-does-not-accept-comma-as-decimal-separator/48247324#48247324) to understand how it works –  Sep 02 '18 at 22:11
  • @StephenMuecke Thanks for your answer. Actually I already tried that suggestion also but without success. Maybe I am facing a diferent issue, please check my "Suggestion D" update. I concluded that my DB accepts comma as decimal separator but I cannot send a number to it with comma even if I hardcoded it. It looks like MVC always replace the comma with a dot and try to insert the number with the dot in the DB. – newhouse-pt Sep 03 '18 at 07:23

0 Answers0