Ajax form and UpdateTargetId after submitting data

2019-07-18 20:31发布

问题:

On my view, I have 2 partial views.

  • 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.

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

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!

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

ASP.NET MVC AJAX change UpdateTargetId if ModelState is invalid

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?

回答1:

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