我試圖將表單提交給控制器操作,並根據OnSuccess或OnFailure處理響應。問題是,即使數據無效並且我未通過ModelState.IsValid測試,也會調用OnSuccess方法。應該調用OnFailure方法。即使數據不好,Ajax.BeginForm也會觸發OnSuccess方法
筆者認爲:
@using (Ajax.BeginForm("UpdateCategory", "Home", null, new AjaxOptions { HttpMethod = "Post", UpdateTargetId = "categoryForm", OnSuccess = "alert('success');", OnFailure = "alert('failure');" }, new { id = "formEditCategory" }))
{
@Html.ValidationSummary(true)
@Html.HiddenFor(model => model.CategoryID)
<div>
<div class="editor-label">
@Html.LabelFor(model => model.CategoryName)
</div>
<div class="small-multiline-field">
@Html.EditorFor(model => model.CategoryName)
</div>
<div class="validationMsg">
@Html.ValidationMessageFor(model => model.CategoryName)
</div>
</div>
}
我的控制器操作:
[HttpPost]
public ActionResult UpdateCategory(CategoryVM category)
{
try
{
if (ModelState.IsValid)
{
var itemService = new ItemViewModels();
itemService.UpdateCategory(category);
}
}
catch (DataException)
{
//Log the error (add a variable name after DataException)
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator.");
}
return PartialView("EditCategoryInfo", category);
}
我的視圖模型:
public class CategoryVM
{
public int CategoryID { get; set; }
[StringLength(75, ErrorMessage = "Category Name must be under 75 characters.")]
[DataType(DataType.MultilineText)]
[Display(Name = "Name")]
public string CategoryName { get; set; }
[StringLength(3800, ErrorMessage = "Category Description must be under 3800 characters.")]
[DataType(DataType.MultilineText)]
[Display(Name = "Description")]
[AllowHtml]
public string CategoryDesc { get; set; }
[Display(Name = "Display on Web")]
public bool DisplayOnWeb { get; set; }
}
所以,如果我進入超過75個字符類別名稱字段中輸入字符串我可以看到表單未通過ModelState.IsValid測試,並且視圖被髮送回註釋「類別名稱必須少於75個字符」。錯誤信息。但不是觸發OnFailure事件,而是觸發OnSuccess事件。爲什麼?
在此先感謝。
什麼可能已經取得了這樣的回答工作會一直,如果你已經張貼的解決方案,而不是一個鏈接到解決方案。只是一個小費。我贊成你,因爲我喜歡你鏈接的解決方案。 –