繁体   English   中英

MVC 3 MusicStore验证错误消息定义

[英]mvc 3 MusicStore validation error message definition

我刚刚开始学习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; }
    }
}

将代码粘贴到解决方案中后,我可以看到验证有效,但是我不了解一件事: GenreArtist的下拉列表中没有“ required”标签; 如果我什么也没有选择,然后单击“保存”按钮,则会显示以下错误消息: “必须输入流派字段”“需要艺术家字段”

我回到前几页,发现在第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);
}

不可将非空标量值(例如int,DateTime,decimal等)视为必需项,因为您不能在其中插入null。 因此,如果您不想验证这些字段,请使用int吗? 用于非必需的int。

     public int? GenreId { get; set; }
     public int? ArtistId { get; set; }

无需对字符串数据类型执行此操作,因为字符串可以为空。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM