查看组件未在第二次提交时检测到/返回Ajax请求 [英] View Component not detecting/returning Ajax request on 2nd submit

查看:77
本文介绍了查看组件未在第二次提交时检测到/返回Ajax请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到了一个非常奇怪的问题,我的ajax发布请求在页面加载后的第一次运行良好,但是如果我再次提交表单而不进行页面刷新,那么内容将返回到整个页面而不是更新DIV.我花了几天的时间来寻找答案并通过反复试验,我怀疑问题与Request.Headers["X-Requested-With"]在第二次提交时为空有关.请注意,我正在向ajax请求返回一个View组件,而我的ajax代码在一个单独的js文件中.

I've got a really strange problem where my ajax post request works fine the first time after the page has loaded but if I submit my form again without doing a page refresh then the contents are returned to the whole page instead of just updating the DIV. I've spent days on this looking for answers and through trial and error and I suspect the issue relates to Request.Headers["X-Requested-With"] being empty on 2nd submit. Note that I am returning a View Component to the ajax request and my ajax code is in a separate js file.

查看组件(它包含提交的表单,当ajax请求返回时将被替换.在加载或刷新页面后,它可以正常工作)

@model MSIC.Models.ClientViewModels.VisitMovementViewModel
@{
    bool inProgress = (bool)ViewData["inProgress"];
}
<form asp-controller="Client" asp-action="VisitMovement" asp-route-id="@Model.VisitMovementID" id="formVisitAction" method="post" onsubmit="AjaxSubmit(this)">
    <input asp-for="VisitID" type="hidden" />
    <input asp-for="StageNo" type="hidden" />
    <input type="hidden" id="replaceID" name="replaceID" value="#ClientVisit" />
    <input type="hidden" id="submitAction" name="submitAction" />
    <div class="col-md-9 no-padding">
        <input type="text" id="visitMovementComment" name="visitMovementComment" class="form-control" placeholder="Comment..." required>
    </div>
    <div class="input-group col-md-3">
        <input type="text" id="visitMovementBoothNo" name="visitMovementBoothNo" class="form-control" placeholder="Booth..." required>
        <div class="input-group-btn">
            <button type="button" class="btn btn-success dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false" @((inProgress) ? "" : "disabled")>Action <span class="caret"></span></button>
            <ul class="dropdown-menu dropdown-menu-right">
                @if (Model.Buttons != null)
                {
                    foreach (var item in Model.Buttons)
                    {
                        if (item.beforeDivider)
                        {
                            <li><button type="@item.Type" name="@item.Name" class="btn btn-link btn-block btn-flat" value="@item.Value" onclick="@item.OnClick">@item.Text</button></li>
                        }
                    }
                    <li role="separator" class="divider"></li>
                    foreach (var item in Model.Buttons)
                    {
                        if (!item.beforeDivider)
                        {
                            <li><button type="@item.Type" name="@item.Name" class="btn btn-link btn-block btn-flat" value="@item.Value" onclick="@item.OnClick">@item.Text</button></li>
                        }
                    }
                }
            </ul>
        </div>
    </div>
</form>

Ajax请求位于单独的JS文件中(调试此文件时,所有操作均按预期第一次运行,但是在返回View Component并第二次提交表单后,成功,错误,完整功能永远不会触发,返回的数据会加载到整个页面中)

function AjaxSubmit(form) {
    $form = $(form);
    var replaceID = $('input#replaceID', $form).val();
    var formData = $form.serialize();

    if (!$form[0].checkValidity()) {
        return false;
    }

    $form.submit(function (e) {
        e.preventDefault();
        $.ajax({
            url: $form.attr('action'),
            type: $form.attr('method'),
            data: formData,
            async: true,
            processData: false,
            cache: false,
            success: function (data) {
                $(replaceID).html(data);
            },
            error: function (xhr, status, error) {
                console.log(xhr.status + " - " + error);
            },
            complete: function (data) {
                console.log(data);
            }
        });
    });
}

操作方法(我怀疑问题可能与Request.Headers["X-Requested-With"]在第二次提交时为空有关,因此MVC并未意识到这是ajax请求,因此将结果返回到页面而不是返回到页面) ajax请求)

Action Method (I suspect the issue may be related to the Request.Headers["X-Requested-With"] being Empty on the 2nd submit and therefore MVC does not realise this is an ajax request hence returns the result to the page instead of returning it to the ajax request)

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> VisitMovement(int id, int submitAction, int? visitMovementBoothNo, string visitMovementComment, VisitMovementViewModel model)
{
    var test1 = Request.ContentType; //1ST REQUEST = "application/x-www-form-urlencoded; charset=UTF-8", 2ND REQUEST = "application/x-www-form-urlencoded"
    var test2 = Request.Headers["X-Requested-With"]; //1ST REQUEST = "XMLHttpRequest", 2ND REQUEST = Empty

    try
    {
        if (ModelState.IsValid)
        {
            bool complete = false;

            switch (submitAction)
            {
                case 2: //Proceed to Stage 2
                    model.StageNo = 2;
                    break;
                case 3: //Proceed to Stage 3
                    model.StageNo = 3;
                    break;
                case 4: //Complete Visit
                    complete = true;
                    break;
                default:
                    return BadRequest("Could not determine action.");
            }

            await visitAPI.VisitMovement(id, model.VisitID, submitAction, model.StageNo, visitMovementBoothNo, visitMovementComment, complete);

            return ViewComponent("ClientVisit", new { visitID = model.VisitID });

        }
        else
        {
            return BadRequest(ModelState);
        }

    }
    catch (Exception ex)
    {
        return StatusCode(500, ex.Message);
    }

}

如果我的假设是正确的,为什么在第二次提交ajax请求时未发送正确的标头,我该如何解决?如果没有,那还有什么可能会出错?

If my assumption is correct why is the ajax request not sending the the correct headers when it is submitted the 2nd time and how can i fix it? If not what else could be going wrong?

推荐答案

我认为问题是当数据/视图组件返回时,表单提交事件丢失了.我通过将我的ajax帖子更改为以下内容来解决了这个问题...

I think the problem was the form submit event was being lost when the data/view component returned. I solved the problem by changing my ajax post to below...

$(document).on('submit', 'form.ajax-form', function (e) {
    var replaceID = $('input#replaceID', $(this)).val();
    var replaceType = $('input#replaceType', $(this)).val();
    e.preventDefault();
    $.ajax({
        url: $(this).attr('action'),
        type: $(this).attr('method'),
        data: $(this).serialize(),
        async: true,
        processData: false,
        cache: false,
        success: function (data) {
            $(replaceID).html(data);
        },
        error: function (xhr, status, error) {
            AjaxOnFailure(xhr, status, error);
        }
    });
});

这篇关于查看组件未在第二次提交时检测到/返回Ajax请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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