【发布时间】:2014-08-14 02:38:28
【问题描述】:
我刚开始学习 C# 和 SQL,现在正在学习 MVC3。我从http://mvcmusicstore.codeplex.com/ 下载了免费的 ASP.NET MVC 音乐商店教程 - 版本 3.0b,这是一个 135 页的文件。当我阅读第 76 页时,它是关于使用 Data Annotation 属性进行模型验证的。这是代码:
namespace MvcMusicStore.Models
{
[Bind(Exclude = "AlbumId")]
public class Album
{
[ScaffoldColumn(false)]
public int AlbumId { get; set; }
[DisplayName("Genre")]
public int GenreId { get; set; }
[DisplayName("Artist")]
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, 100.00, ErrorMessage = "Price must be between 0.01 and 100.00")]
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; }
}
}
在解决方案中粘贴代码后,我可以看到验证有效,但有一点我不明白:Genre 的下拉列表没有“必需”标签和艺术家;如果我什么都不选,然后单击保存按钮,则会显示以下错误消息:“需要类型字段”和“需要艺术家字段”
我回到前面的页面,发现它在第 65 页上显示“使用 @HTML.ValidationMessageFor HTML Helper 自动显示验证错误”,但是当我在整个解决方案中搜索这两个句子时,我没有得到任何结果。
谁能说出两条错误信息的定义在哪里?
在源码中,下拉列表定义如下: // // 发布:/StoreManager/Edit/5
[HttpPost]
public ActionResult Edit(Album album)
{
if (ModelState.IsValid)
{
db.Entry(album).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
ViewBag.GenreId = new SelectList(db.Genres, "GenreId", "Name", album.GenreId);
ViewBag.ArtistId = new SelectList(db.Artists, "ArtistId", "Name", album.ArtistId);
return View(album);
}
【问题讨论】:
-
这个post 及其链接解释了为什么以及您可以做些什么来更改消息。
标签: c# asp.net-mvc validation