Reputation: 2441
I am trying to make an example MvcMusicStore
application from MSDN. My code of Model class is:
public class Album
{
public int Id { get; set; }
public int GenreId { get; set; }
public int ArtistId { get; set; }
[Required(ErrorMessage = "An Album Title is required")]
[StringLength(160)]
public string Title { get; set; }
[Required(ErrorMessage = "Price is required")]
[Range(0.01, double.MaxValue, ErrorMessage = "Price must be positive")]
public decimal Price { get; set; }
[DisplayName("Album Art URL")]
[StringLength(1024)]
public string AlbumArtUrl { get; set; }
public virtual Genre Genre { get; set; }
public virtual Artist Artist { get; set; }
}
And I generated the code for Controller by Scaffolding (CRUD template). But I have got problem with validation of Price in my View. This is the fragment of my Razor code in view:
<div class="editor-label">
@Html.LabelFor(model => model.Price)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Price)
@Html.ValidationMessageFor(model => model.Price)
</div>
Everything looks good, client-side validation works as expected, but problem lies by the server-side validation. This is the method code in Controller:
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(Album album)
{
if (ModelState.IsValid)
{
db.Albums.Add(album);
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.GenreId = new SelectList(db.Genres, "Id", "Name", album.GenreId);
ViewBag.ArtistId = new SelectList(db.Artists, "Id", "Name", album.ArtistId);
return View(album);
}
In the beginning of this method I inserted a break point. Debugger says that album.Price
always equals 0. I suppose it is translation from text in textbox to decimal problem in Controller's method. I always inserted values point separated such as 10.99, 12.65, 19.99, etc. It only works with integer values like 3, 10, 14, etc.
How to solve it?
Upvotes: 4
Views: 3058
Reputation: 1038710
You could explicitly set the culture to some culture in which the decimal separator is .
:
<globalization uiCulture="en-US" culture="en-US" />
Upvotes: 4