ASP.NET Core+ADO.NET下AJAX提交后无法跳转至Index页面问题排查
问题原因
你用jQuery AJAX提交请求时,服务器返回的RedirectToAction不会触发浏览器自动跳转——AJAX是异步请求,只会接收服务器响应,不会主动执行重定向操作,这就是数据更新后页面没跳转的核心原因。
解决方案
方案1:后端返回跳转指令,前端处理跳转
修改Controller中ModelState有效时的返回逻辑,把重定向改成返回带跳转地址的JSON:
[HttpPost] [ValidateAntiForgeryToken] public IActionResult AddOrEdit(int id, [Bind("BookID,Title,Author,Price")] BookViewModel bookViewModel) { if (ModelState.IsValid) { // 数据库操作代码保持不变 using (SqlConnection sqlConnection = new SqlConnection(_configuration.GetConnectionString("BookConnection"))) { sqlConnection.Open(); SqlCommand sqlCmd = new SqlCommand("BookAddOrEdit", sqlConnection); sqlCmd.CommandType = CommandType.StoredProcedure; sqlCmd.Parameters.AddWithValue("BookID", bookViewModel.BookID); sqlCmd.Parameters.AddWithValue("Title", bookViewModel.Title); sqlCmd.Parameters.AddWithValue("Author", bookViewModel.Author); sqlCmd.Parameters.AddWithValue("Price", bookViewModel.Price); sqlCmd.ExecuteNonQuery(); } // 替换原RedirectToAction,返回跳转地址 return Json(new { isValid = true, redirectUrl = Url.Action(nameof(Index)) }); // 注释掉原来的重定向和旧的JSON返回 // return RedirectToAction(nameof(Index)); // return Json(new { isValid = true, html = Helper.RenderRazorViewToString(this, "Index") }); } return Json(new {isValid= false,html = Helper.RenderRazorViewToString(this,"AddOrEdit", bookViewModel) }); }
然后在前端AJAX的成功回调中,判断返回的isValid为true时,手动跳转页面:
// 假设你的AJAX代码类似这样 $.ajax({ url: "/Book/AddOrEdit", type: "POST", data: $("form").serialize(), // 或者FormData,根据你的表单结构调整 headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() // 防伪造令牌 }, success: function(res) { if (res.isValid) { // 跳转到Index页面 window.location.href = res.redirectUrl; } else { // 验证失败时更新弹窗内容,保持原来的逻辑 $("#yourModalContent").html(res.html); } } });
方案2:放弃AJAX,使用普通表单提交(不推荐,会刷新整个页面)
如果不需要无刷新提交,可以把弹窗里的表单改成普通表单,设置action="/Book/AddOrEdit"和method="post",这样提交后服务器的RedirectToAction会直接触发浏览器跳转,但会刷新整个页面,不符合弹窗的无刷新体验。
关键说明
AJAX请求的核心是异步获取数据,浏览器不会自动处理服务器返回的重定向响应,必须通过前端JS代码手动执行window.location.href来完成跳转。你原来的RedirectToAction只有在普通表单提交(非AJAX)时才会生效。
内容的提问来源于stack exchange,提问作者Prudvi
相关产品推荐
相关产品推荐

