ASP.NET MVC 5 double value always 0.0 in controlle

2019-08-31 07:48发布

问题:

In my ASP.NET MVC 5 app I have form where user can enter price. Of course that value isn't always integer so I defined it as double in my Model. And when User enter some value, e.g. 10000.00 and press submit, model sent to controller always have 0.0 value for property price. Any ideas why ?

My property is defined in model as:

        [Required(ErrorMessageResourceType = typeof(Resources), ErrorMessageResourceName = "_errorEmpty")]
        [Display(Name = "_carPrice", ResourceType = typeof(Resources))]
        public Decimal Cijena { get; set; }

In my view I'm using it like this:

           <div class="form-group">
                @Html.LabelFor(model => model.Cijena, new { @class = "col-md-2 control-label" })
                <div class="col-md-10">
                    @Html.TextBoxFor(model => model.Cijena, new { @class = "form-control", id = "cijena" })
                    @Html.ValidationMessageFor(model => model.Cijena)
                </div>
            </div>

And my Controller:

 [HttpPost]
 [ValidateAntiForgeryToken]
 public ActionResult AddNewCar([Bind(Include = "Model, GodinaProizvodnje, GodinaKupnje, DrugiID, Cijena, RegOznaka, RegOd, RegDo, SelectedCityId")] AddCar car)
    {
    .
    .
    .
    }

And when model is passed from view to controller on submit value for Price is always 0. I have tried defined property as Decimal, Double, Float ... always 0 http://prntscr.com/4hel3f

回答1:

I guess you're not running your app in en-us culture.

Try changing the thread culture to en-us so that decimal separator considered by double.Parse is "." instead of ",".

<configuration>
<system.web>
    <globalization
       enableClientBasedCulture="true"        
       culture="en-GB"/>
</system.web>

Alternatively you can create a custom binder for double/float.