我正在尝试将表单提交给控制器操作并根据 OnSuccess 或 OnFailure 处理响应。问题是,即使数据无效并且我未能通过 ModelState.IsValid 测试,也会调用 OnSuccess 方法。应该调用 OnFailure 方法。
我的观点:
@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; }
}
因此,如果我在 CategoryName 字段中输入超过 75 个字符的字符串,我可以看到该表单未通过 ModelState.IsValid 测试,并且视图被发回,并带有“类别名称必须小于 75 个字符”的注释。错误信息。但它不是触发 OnFailure 事件,而是触发 OnSuccess 事件。为什么?
提前致谢。