[英]ExpressiveAnnotations works for Add View, but not Edit View MVC 5
在我的metadata.cs文件中,當我在AddRecord Controller Action中單擊_db.SaveChanges()時,此方法適用。 “ [AssertThat(”適用於Add SaveChanges(),但不適用於Edit SaveChanges()。“ [Required]”適用於兩者。“ sss”不會傳遞Add SaveChanges(),它將傳遞Edit SaveChanges() 。
[Required(ErrorMessage = "Email is required")]
[AssertThat("IsEmail(Email)",ErrorMessage="Valid email format required")]
public string Email { get; set; }
換句話說,要進行解釋:在EditRecord Controller Action中,僅正常的DataAnnotation會觸發,而我安裝的ExpressiveAnnotations不會觸發,並且在條件注釋中效果很好。 添加和編輯動作都在同一控制器中。 並在單步執行代碼時都使用Overide SaveChanges(),“編輯操作”在覆蓋的最后一行中斷,並顯示錯誤中的錯誤內容,但不像Add View SaveChanges()那樣在輸入下顯示ErrorMessage。
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();
這是我執行添加操作的方法:
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddStoreAccount(StoreAccounts storeaccounts)
{
if (ModelState.IsValid) {
_db.StoreAccounts.Add(storeaccounts);
{
_db.SaveChanges();
哦,你要開槍我。 也許不吧。 我嘗試了一些方法,但效果很好。 我的常規DataAnnotations用於Edit View輸入驗證,例如:[Required],[StringLength]和[RegularExpression]。 ...但不適用於[RequiredIf]和[AssertThat]之類的ExpressiveAnnotation。
Add和Edit的SaveChanges()重寫均相同,但ModelState.IsValid的Edit Save操作未填充ExpressiveAnnotation錯誤。
所以。 。 。 因為添加是在模型中發送的,所以我決定將模型添加到Edit操作中的參數中:
加
public ActionResult AddStoreAccount(StoreAccounts storeaccounts)
編輯
public ActionResult EditStoreAccount(int id, FormCollection formValues, StoreAccounts storeaccounts)
現在,我沒有對即將到來的模型(StoreAccounts storeaccounts)進行任何限制。 MetaData類看到了它並填充了ModelState,因此IsValid為false。 然后繼續將錯誤消息放到輸入下方,就像常規的DataAnnotations一樣,沒有YSOD。
哦,要弄清楚這個MVC東西已經很漫長。 他們想要像MS Access和/或Ruby LOL一樣糟糕,但是他們還沒有到位。
我希望這10個小時的拔發功能可以幫助其他人擺脫StackOverflow。 也許有人可以發表評論並解釋發生了什么。 請隨意發表評論。 我尋求啟示。 如果有人想提出一個更簡潔的答案來解釋這個難題,我很樂意選擇他們的答案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.