ModelState无效时提交数据后的Ajax表单和UpdateTargetId [英] Ajax form and UpdateTargetId after submitting data when ModelState is Invalid

查看:207
本文介绍了ModelState无效时提交数据后的Ajax表单和UpdateTargetId的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我看来,我有2个局部视图.

On my view, I have 2 partial views.

  • 第一个局部视图(PV1):用户可以在文本框中键入一个项目并通过ajax表单提交.
  • 第二部分视图(PV2):用户可以看到以前提交的项目的列表.
  • 1st partial view (PV1): user can type an item in a textbox and submit through an ajax form.
  • 2nd partial view (PV2): user can see a list of items previously submitted.

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

The PV1 uses UpdateTargetId on a div on the PV2 because we would like to update our list with the newly added item.

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

Everything works well when items submitted on the PV1 are valid. It doesn't work when ModelState.IsValid == false when ajax form is submitted. It doesn't work because the UpdateTargetId is located on the PV2, and I need to update the PV1 for showing the ModelState Errors. So we encounter with duplicate of the PV1 on the PV2!

下面是另一个关于类似问题的stackoverflow帖子,但是没有提供解决方案.

Below is another stackoverflow post on a similar problem but no solutions has been provided.

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

我认为可以使用 Json 替代方案,但是我想知道我们是否可以调整标准的 Ajax形式方法来满足我们的需求?

I think a Json alternative may be a solution but I'm wondering if we can adapt the standard Ajax form method to suit our need here?

推荐答案

代替使用UpdateTargetId,您可以尝试使用OnComplete:

Instead of using UpdateTargetId, you could try using OnComplete:

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

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

and inside this handler test whether there is an error in the resulting view:

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

这篇关于ModelState无效时提交数据后的Ajax表单和UpdateTargetId的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆