【问题标题】:mvc 3 MusicStore validation error message definitionmvc 3 MusicStore 验证错误信息定义
【发布时间】: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


【解决方案1】:

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

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

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

【讨论】:

  • 我需要验证,但我不明白为什么会自动为 2 个下拉列表创建消息。在源码中,下拉列表定义如下: '// // POST: /StoreManager/Edit/5 [HttpPost] public ActionResult Edit(Album album) { if (ModelState.IsValid) { db.Entry(专辑).State = EntityState.Modified; db.SaveChanges(); return RedirectToAction("索引"); } ViewBag.GenreId = new SelectList(db.Genres, "GenreId", "Name", album.GenreId); ViewBag.ArtistId = new SelectList(db.Artists, "ArtistId", "Name", album.ArtistId);返回视图(专辑); }'
  • 正如我所说的 int 被自动认为是必需的。不管你是否定义它。
  • 好吧,我会忘记的。我试图添加“?”在“int”之后,它确实跳过了验证检查。我还将 [DisplayName("Genre")] 更改为其他名称,因此如果我使用验证,错误消息的名称会随着名称的变化而变化。
猜你喜欢
  • 1970-01-01
  • 2011-04-04
  • 1970-01-01
  • 1970-01-01
  • 2014-03-25
  • 2021-08-12
  • 2016-10-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多