0

在我的metadata.cs文件中,当我在AddRecord Controller Action中点击_db.SaveChanges()时,它适用。 “[AssertThat(”适用于​​添加SaveChanges(),但不适用于Edit SaveChanges() “[必需的]”适用于两者,“sss”不会传递Add SaveChanges(),它会传递Edit SaveChanges )ExpressiveAnnotations适用于添加视图,但不适用于编辑视图MVC 5

[Required(ErrorMessage = "Email is required")] 
[AssertThat("IsEmail(Email)",ErrorMessage="Valid email format required")] 
public string Email { get; set; } 

要换句话说解释: 在EditRecord控制器动作只是正常DataAnnotation火灾,而不是我安装和作品真的很好用条件标注的添加和编辑操作都在同一个控制器的ExpressiveAnnotations。并且在遍历代码时都使用Override SaveChanges(),编辑动作在重写的最后一行中断,并显示错误中的错误,但在输入下不显示ErrorMessage,如Add View SaveChanges()

public override int SaveChanges() 
    { 
     try 
     { 
      return base.SaveChanges(); 
     } 
     catch (DbEntityValidationException ex) 
     { 
      // Retrieve the error messages as a list of strings. 
      var errorMessages = ex.EntityValidationErrors 
        .SelectMany(x => x.ValidationErrors) 
        .Select(x => x.ErrorMessage); 

      // Join the list to a single string. 
      var fullErrorMessage = string.Join("; ", errorMessages); 

      // Combine the original exception message with the new one. 
      var exceptionMessage = string.Concat(ex.Message, " The validation errors are: ", fullErrorMessage); 

      // Throw a new DbEntityValidationException with the improved exception message. 
      throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors); 

这最后一行就是编辑操作出现错误而终止:

throw new DbEntityValidationException(exceptionMessage, ex.EntityValidationErrors); 

我通过研究StackOverflow的上述异常循环和覆盖,非常感谢你,它确实抓住了ExpressiveAnnotations错误时,电子邮件不适合有效的格式,但它与死亡黄色屏幕窒息。添加或拒绝记录后,我的添加动作不会窒息并继续播放。

我希望我已经提供了足够的信息。我看了两个观点,他们几乎完全相同。

几个小时后

我想也许调用操作时,我不会在视图中的正确的模式发送。

[AcceptVerbs(HttpVerbs.Post)] 
public ActionResult EditStoreAccount(int id, FormCollection formValues) 
{ 

    var accountToUpdate = _db.StoreAccounts.First(m => m.AccountID == id); 

    if (ModelState.IsValid) 
    { 
//fill up accountToUpdate 

_db.SaveChanges(); 

这里是我做的添加操作:

​​

回答

0

哦,你要拍我。也许不会。我尝试了一些,它的工作。 我的常规DataAnnotations正在编辑视图输入验证,如:[必需的],[字符串长度]和[RegularExpression]。 ...但不包括[RequiredIf]和[AssertThat]等表达式注释。

SaveChanges()覆盖与Add和Edit相同,只是ModelState.IsValid没有被编辑保存操作的ExpressiveAnnotation错误填充。

所以。 。 。由于Add是在模型中发送的,因此我决定将模型添加到进入“编辑”操作的参数中。

添加

public ActionResult AddStoreAccount(StoreAccounts storeaccounts) 

编辑

public ActionResult EditStoreAccount(int id, FormCollection formValues, StoreAccounts storeaccounts) 

现在,我没有做nuthin'在(StoreAccounts storeaccounts)未来的模式。 MetaData类看到它并填充ModelState,所以IsValid为false。然后继续将错误消息放在输入的下面,就像常规的DataAnnotations和没有YSOD一样。

哦,这是一个漫长的艰难旅程,弄清楚这个MVC的东西了。他们想让它像MS Access和/或Ruby LOL一样糟糕,但它们还没有完成。

我希望这10小时的头发拉动将帮助其他人在StackOverflow出。也许有人可以评论和解释发生了什么事。请随意发表评论。我寻求启示。如果有人想对这个难题作出更简洁的回答,我会很乐意选择他们的答案。

相关问题