【问题标题】:Ajax form and UpdateTargetId after submitting data when ModelState is InvalidModelState无效时提交数据后的Ajax表单和UpdateTargetId
【发布时间】:2011-11-06 12:02:57
【问题描述】:

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

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

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

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

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

ASP.NET MVC AJAX change UpdateTargetId if ModelState is invalid

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

【问题讨论】:

    标签: ajax asp.net-mvc modelstate


    【解决方案1】:

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

    @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);
        }
    }
    

    【讨论】:

    • 非常感谢,我很高兴看到围绕 Ajax.Beginform 助手的解决方案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多