我正在尝试制作一个来自MSDN的示例MvcMusicStore
应用程序。我的模型类代码如下:
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; }
}
我使用脚手架(CRUD模板)生成了Controller的代码。但是在我的视图中,我遇到了价格验证的问题。这是我的Razor代码片段:
<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>
一切看起来都很好,客户端验证按预期工作,但问题在于服务器端验证。这是控制器中的方法代码:
[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);
}
在这个方法的开头,我插入了一个断点。调试器显示
album.Price
始终等于0。我认为这是从文本框中转换为控制器方法中的十进制问题。我总是插入以点分隔的值,例如10.99、12.65、19.99等。它只适用于像3、10、14等整数值。如何解决?