即使数据不好,Ajax.BeginForm也会触发OnSuccess方法

BKa*_*una 2 forms asp.net-mvc ajax.beginform razor

我正在尝试将表单提交给控制器操作并基于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>
}
Run Code Online (Sandbox Code Playgroud)

我的控制器动作:

[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);
}
Run Code Online (Sandbox Code Playgroud)

我的ViewModel:

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; }
}
Run Code Online (Sandbox Code Playgroud)

因此,如果我在CategoryName字段中输入超过75个字符的字符串,我可以看到该表单未通过ModelState.IsValid测试,并且视图将以"类别名称必须小于75个字符"的形式发回.错误信息.但是它不是触发OnFailure事件,而是触发OnSuccess事件.为什么?

提前致谢.

Jac*_*ack 6

由于您已捕获异常,因此返回的是具有HTTP状态代码200的PartialView.这就是OnSuccess被触发的原因.

您可以做的是明确将响应代码设置为400(错误请求)

[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.");
        Response.StatusCode = 400;
    }

    return PartialView("EditCategoryInfo", category);
}
Run Code Online (Sandbox Code Playgroud)