我正在尝试创建示例验证属性以了解有关 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()
被调用了两次
- 在 Controller Action 之前,因为在调用 Action 之前验证数据
- 在
db.SaveChanges()
上,因为数据库上下文也进行验证
关于c# - ASP.Net MVC 4 自定义验证属性 isValid 被调用两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34556877/