Jacob Jedryszek
Jacob Jedryszek

Reputation: 6470

double values in model

I have complex model with double values...I have problem with pass them into object. When I pass integer values (like 4 or 5) everything is ok, but when I try pass double value (like 4.3 or -23.3) during debugging I see that model has 0.0.

public class Coordinates
{
    public int ID { get; set; }

    [Required]
    public double Latitude { get; set; }

    [Required]
    public double Longitude { get; set; }
}

    [HttpPost]
    public ActionResult Edit(Place place)
    {
        var updatedPlace = db.Place.Include(c => c.Country).Include(c => c.Coordinates).Where(p => p.ID == place.ID).SingleOrDefault();
        updatedPlace.Coordinates.Latitude = place.Coordinates.Latitude;
        updatedPlace.Coordinates.Longitude = place.Coordinates.Longitude;
        updatedPlace.Country = db.Country.Find(place.Country.ID);
        updatedPlace.Description = place.Description;
        updatedPlace.Name = place.Name;
        db.Entry(updatedPlace).State = EntityState.Modified;
        db.SaveChanges();
        return RedirectToAction("Index");
    }

In view I use:

@Html.EditorFor(model => model.Coordinates.Latitude)
@Html.EditorFor(model => model.Coordinates.Longitude)

Upvotes: 1

Views: 446

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038720

The default model binder uses the current culture setting when parsing the request values into your model properties. So for example if you have culture set to auto then it will use that of the client browser (Accept-Language HTTP request header). And if you have a client from France (fr-FR) and he enters 4.3 in the input field the default model binder won't be able to parse it back to a double because in France they use , as decimal separator not ..

So you could set the culture in the web.config to some fixed value:

<globalization culture="en-US" uiCulture="en-US" />

Or if you need to support multiple scenarios and cultures you could also write a custom model binder.

Upvotes: 2

Related Questions