2

在我看来,我有两个部分观点。

  • 第一个部分视图(PV1):用户可以在文本框中输入项目并通过 ajax 表单提交。
  • 第二部分视图(PV2):用户可以看到以前提交的项目列表。

PV1UpdateTargetId在 PV2 上的 div 上使用,因为我们想用新添加的项目更新我们的列表。

当 PV1 上提交的项目有效时,一切正常。ModelState.IsValid == false提交ajax表单时不起作用。它不起作用,因为 UpdateTargetId 位于 PV2 上,我需要更新 PV1 以显示 ModelState 错误。所以我们在 PV2 上遇到了 PV1 的副本!

下面是关于类似问题的另一篇 stackoverflow 帖子,但未提供任何解决方案。

如果 ModelState 无效,ASP.NET MVC AJAX 更改 UpdateTargetId

我认为Json替代方案可能是一种解决方案,但我想知道我们是否可以调整标准的Ajax 表单方法来满足我们的需求?

4

1 回答 1

7

UpdateTargetId您可以尝试使用,而不是使用OnComplete

@using (Ajax.BeginForm(new AjaxOptions { OnComplete = "complete" }))
{
    ...
}

并在此处理程序中测试结果视图中是否存在错误:

function complete(result) {
    var isError = $('span.field-validation-error', result.responseText).length > 0;
    if (isError) {
        // there was an error => we update the container of the form
        $('#frmContainer').html(result.responseText);
    } else {
        // no error => we hide validation errors and update the result container
        $('#frm .field-validation-error').hide();
        $('#frm .input-validation-error').removeClass('input-validation-error');
        $('#result').html(result.responseText);
    }
}
于 2011-11-07T07:22:58.867 回答