C# mvc 3 MusicStore验证错误消息定义
我刚开始学习C和SQL,现在正在学习C# mvc 3 MusicStore验证错误消息定义,c#,asp.net-mvc,validation,C#,Asp.net Mvc,Validation,我刚开始学习C和SQL,现在正在学习MVC3。我下载了免费的ASP.NETMVC音乐商店教程-版本3.0b,其中包含一个135页的文件。当我阅读第76页时,它是关于使用数据注释属性进行模型验证的。代码如下: namespace MvcMusicStore.Models { [Bind(Exclude = "AlbumId")] public class Album { [ScaffoldColumn(false)] public int A
MVC3
。我下载了免费的ASP.NETMVC音乐商店教程-版本3.0b,其中包含一个135页的文件。当我阅读第76页时,它是关于使用数据注释
属性进行模型验证的。代码如下:
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; }
}
}
将代码粘贴到解决方案中后,我可以看到验证工作正常,但有一件事我不明白:对于流派和艺术家的下拉列表,没有“必需”标记;如果我不选择任何内容,并单击保存按钮,将显示以下错误消息:“流派字段是必需的”和“艺术家字段是必需的”
我回到前几页,发现第65页上写着“使用@HTML.ValidationMessageFor HTML Helper
自动显示验证错误”,但当我在整个解决方案中搜索这两句话时,没有得到任何结果
谁能说出这两条错误消息的定义在哪里
在源代码中,下拉列表定义如下:
//
//POST:/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);
}
不可为null的标量值(如int、DateTime、decimal等)始终被视为必需的,因为您不能将null插入其中。所以,如果您不想验证这些字段,那么使用int?对于非必需的int
public int? GenreId { get; set; }
public int? ArtistId { get; set; }
无需对字符串数据类型执行此操作,因为字符串可为空 我需要验证,但我不明白为什么会自动为2个下拉列表创建消息。在源代码中,下拉列表的定义如下:'///POST:/StoreManager/Edit/5[HttpPost]公共操作结果编辑(Album Album){if(ModelState.IsValid){db.Entry(Album.State).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);返回视图(album);}'如我所说,int自动视为必需。不管你是否定义它是必需的。好吧,我会忘记它的。我尝试在“int”之后添加“?”,但它确实跳过了验证检查。我还将[DisplayName(“流派”)]更改为其他名称,因此如果我使用验证,则错误消息的名称会随着名称的更改而更改。这及其链接解释了更改消息的原因和方法。