c# - ASP.Net MVC 4 自定义验证属性 isValid 被调用两次

标签 c# asp.net asp.net-mvc validation asp.net-mvc-4

我正在尝试创建示例验证属性以了解有关 MVC 的更多信息。我已经创建了验证属性,但是当我运行应用程序时,验证属性被调用了两次 -> 在调用 Controller 之前和保存 DBContext 之前。我相信这应该只调用一次。你能指导我哪里做错了吗?

验证属性:我正在尝试验证该属性的字数是否超过指定的 maxWords

public class ValidationEx : ValidationAttribute
    {
        int _maxWords = 1;
        public ValidationEx()
            : base("{0} has more too many words")
        {
            _maxWords = 1;
        }

        public ValidationEx(int maxWords):base("{0} has more too many words")
        {
            _maxWords = maxWords;
        }

        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {
            if (value != null)
            {
                string data = value as string;
                if (data.Split(' ').Length > _maxWords)
                {
                    var errorMessage = FormatErrorMessage(validationContext.DisplayName);
                    return new ValidationResult(errorMessage);
                }
            }
            return ValidationResult.Success;
        }
    }

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, "GenreID", "Name", album.GenreID);
            ViewBag.ArtistID = new SelectList(db.Artists, "ArtistID", "ArtistName", album.ArtistID);
            return View(album);
        }

注意:在到达 Controller 之前和执行 db.SaveChanges() 时触发验证

型号:

 public class Album
    {
        public virtual int AlbumID { get; set; }
        public virtual int GenreID { get; set; }
        public virtual int ArtistID { get; set; }

        [Required(ErrorMessageResourceType= typeof(ErrorMessages), ErrorMessageResourceName="TitleRequired")]
        [Display(Name="Movie Name")]
        [ValidationEx()]
        public virtual string Title { get; set; }

        [Range(0,1000)]
        public virtual decimal Price { get; set; }
        public virtual string AlbumArtUrl { get; set; }
        public virtual Genre Genre { get; set; }
        public virtual Artist Artist { get; set; }

        [StringLength(40)]
        public virtual string Description { get; set; }
    }

数据库上下文

public class MusicAlbumStoreDBContext : DbContext
    {
        // You can add custom code to this file. Changes will not be overwritten.
        // 
        // If you want Entity Framework to drop and regenerate your database
        // automatically whenever you change your model schema, add the following
        // code to the Application_Start method in your Global.asax file.
        // Note: this will destroy and re-create your database with every model change.
        // 
        // System.Data.Entity.Database.SetInitializer(new System.Data.Entity.DropCreateDatabaseIfModelChanges<MusicAlbumProject.Models.MusicAlbumStoreDBContext>());

        public MusicAlbumStoreDBContext() : base("name=MusicAlbumStoreDBContext")
        {
        }

        public DbSet<Album> Albums { get; set; }

        public DbSet<Genre> Genres { get; set; }

        public DbSet<Artist> Artists { get; set; }

        public DbSet<Order> Orders { get; set; }
    }

最佳答案

您正在使用与模型和 View 模型相同的类。 MVC 区分这两种类型是有原因的。您确实应该添加一个单独的模型和一个单独的 View 模型类。

IsValid() 被调用了两次

  1. 在 Controller Action 之前,因为在调用 Action 之前验证数据
  2. db.SaveChanges() 上,因为数据库上下文也进行验证

关于c# - ASP.Net MVC 4 自定义验证属性 isValid 被调用两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34556877/

相关文章:

用于 C++ 的 C# 包装器,但仅编译为静态库

asp.net - 适合 ASP.NET 开发(兼容浏览器 UI)的良好 UI 单元测试解决方案?

asp.net - 有哪些选项可用于在 ASP.NET MVC2 中存储应用程序设置?

c# - 将 blob (.bacpac) 转换为 .bacpac 文件以将数据库导入到 SQL Server Azure?

c# - 我如何绑定(bind)我在数据网格列后面的代码中定义的形状?

c# - 自高峰期开始计算柱状图

c# - Web API Controller 返回任务并不总是等待任务完成(puppeteer-sharp)

asp.net-mvc - 有没有办法让Ajax.BeginForm返回JSON并自动更新Form

c# - 在 MVC 4 中选择表的所有 tr 并使用复选框将其发送到 Controller

asp.net-mvc - 如何从 url : asp.net mvc 隐藏操作和 Controller