我正在尝试MvcMusicStore
从 MSDN 制作一个示例应用程序。我的模型类代码是:
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>
一切看起来都很好,客户端验证按预期工作,但问题在于服务器端验证。这是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);
}
在这个方法的开始,我插入了一个断点。调试器说album.Price
总是等于0。我想这是从文本框中的文本转换为控制器方法中的十进制问题。我总是插入点分隔的值,例如 10.99、12.65、19.99 等。它仅适用于整数值,例如 3、10、14 等。
如何解决?