Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is ASP.NET MVC 3 not validating my floats correctly?

I've got a View where I allow input, the fields are set as float in my SQL Server 2008 R2 database and I am using Entity Framwork 4.

In the Entity Framework Model the field looks like this private Nullable<global::System.Double> _TestNumber;

And the View uses an EditorField to allow input like this:

<div class="editor-field">
    @Html.EditorFor(model => model.TestNumber)
    @Html.ValidationMessageFor(model => model.TestNumber)
</div>

I am however getting this error in the Validation Message: The value '13.51' is not valid for TestNumber. I've tried with a comma instead of period, same thing.

Suggestions?

like image 852
Filip Ekberg Avatar asked Jan 13 '11 13:01

Filip Ekberg


People also ask

How do you handle validation in MVC?

In code we need to check the IsValid property of the ModelState object. If there is a validation error in any of the input fields then the IsValid property is set to false. If all the fields are satisfied then the IsValid property is set to true. Depending upon the value of the property, we need to write the code.

Is validation handled differently in Web API then in MVC?

We can perform model validation in MVC in an easy way. In API, when sending the request by the client or user to web API, then before doing the next process, it checks the empty validation and handles the validation error using data annotation in WEB API.


1 Answers

That should work:

View Model:

public class MyViewModel
{
    public double? TestNumber { get; set; }
}

Controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel { TestNumber = 13.51 });
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return View(model);
    }
}

View:

@model AppName.Models.MyViewModel
@{
    ViewBag.Title = "Home Page";
}
@using (Html.BeginForm())
{
    @Html.EditorFor(x => x.TestNumber)
    @Html.ValidationMessageFor(x => x.TestNumber)
    <input type="submit" value="OK" />
}

One thing that you could checkout and which could explain the behavior you are observing is inconsistency between client side culture and server side culture. So for example if you have enabled client-side validation but the client culture uses , as decimal separator then 13.51 will fail client-side validation and if the server culture uses . as decimal separator then 13,51 would fail server side validation. So both 13.51 and 13,51 are failing to validate but on different layers. In order for the server to use the same culture as the client you could set the following the culture to auto in your web.config:

<globalization 
    requestEncoding="utf-8" 
    responseEncoding="utf-8" 
    culture="auto" 
    uiCulture="auto"
/>
like image 80
Darin Dimitrov Avatar answered Sep 28 '22 20:09

Darin Dimitrov