error with decimal in mvc3 - the value is not valid for field

后端 未结 9 1582
北荒
北荒 2020-11-29 08:03

I\'m following [Getting started with ASP.NET MVC 3][1]. And I can\'t add/edit with value of Price = 9.99 or 9,99. It said: \"The value \'9.99\' is not valid for Price.\" and

相关标签:
9条回答
  • 2020-11-29 08:49

    I've tried @Leniel Macaferi but it didn't work for me.

    ModelState.IsValid didn't accept numbers formatted like 7.000,00

    The problem started when I changed the property type from:

    [Column("PRICE")]
    public decimal Price { get; set; }
    

    to

    [Column("PRICE")]
    public decimal? Price { get; set; }
    

    I've also tried to include the globalization on web.config that I had forgotten

    <globalization culture="pt-BR" uiCulture="pt-BR" enableClientBasedCulture="true" />
    

    The only workaround that worked was change back the property to decimal only:

    [Column("PRICE")]
    public decimal Price { get; set; }
    

    and also changed the table column to NOT accept null values

    Hope it helps somebody.

    0 讨论(0)
  • 2020-11-29 08:55

    You can add:

    protected void Application_BeginRequest()
    {
        var currentCulture = (CultureInfo)CultureInfo.CurrentCulture.Clone();
        currentCulture.NumberFormat.NumberDecimalSeparator = ".";
        currentCulture.NumberFormat.NumberGroupSeparator = " ";
        currentCulture.NumberFormat.CurrencyDecimalSeparator = ".";
    
        Thread.CurrentThread.CurrentCulture = currentCulture;
        //Thread.CurrentThread.CurrentUICulture = currentCulture;
    }
    

    To Global.asax (tested on MVC 5.1). It works without changing UICulture for me.

    0 讨论(0)
  • In 2019, this problem is still not solved. Using ASP Core 2.1, my UI is in French (decimal separator= ',') and I couldn't get the validation to work anytime I had a decimal number.

    I found a workaround, not ideal though: I created a french-based CultureInfo but I changed the decimal separator to be the same as in Invariant Culture : '.'.

    This made the trick, my decimal numbers are now displayed US style (but I am ok with it) and validation works.

        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env)
        {
            app.UseHttpsRedirection();
            app.UseStaticFiles();
            app.UseCookiePolicy();
    
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
    
    
            //Culture specific problems
            var cultureInfo = new CultureInfo("fr-FR");
            cultureInfo.NumberFormat.NumberDecimalSeparator = ".";
            System.Threading.Thread.CurrentThread.CurrentUICulture = cultureInfo;
    
        }
    
    0 讨论(0)
提交回复
热议问题