查看组件未在第二次提交时检测/返回Ajax请求

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

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

 @model MSIC.Models.ClientViewModels.VisitMovementViewModel @{ bool inProgress = (bool)ViewData["inProgress"]; } 

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

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

 [HttpPost] [ValidateAntiForgeryToken] public async Task 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请求在第二次提交时没有发送正确的标题,我该如何解决? 如果不是其他什么可能出错?

我认为问题是表单提交事件在数据/视图组件返回时丢失了。 我通过将我的ajaxpost改为下面来解决问题…

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