You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用jQuery Ajax触发时RedirectToAction无法跳转至指定Action问题

问题原因

你遇到的核心问题是Ajax异步请求的特性导致的:当通过Ajax发起DELETE请求时,服务器返回的RedirectToAction(本质是302重定向响应)会被Ajax的回调函数接收,而不是由浏览器自动处理页面跳转——因为Ajax是后台发起的请求,不属于浏览器的主动导航行为。

解决方案

方案1:前端Ajax成功后手动跳转

直接在Ajax的success回调里添加页面跳转代码,不需要修改后端:

$('#deleteButton').click(function (event) {
    event.preventDefault();
    const encodedName = $(this).data('encodedname');
    $.ajax({
        url: `/projects/delete?encodedName=${encodeURIComponent(encodedName)}`,
        type: 'DELETE',
        // 去掉async: false,同步请求会阻塞浏览器,体验极差
        success: function (data) {
            toastr["success"]("Deleted project");
            // 手动跳转到Index页面
            window.location.href = '/projects';
        },
        error: function () {
            toastr["error"]("Something went wrong");
        }
    });
});

方案2:后端返回跳转指令,前端处理

修改后端返回JSON数据,携带跳转地址,让前端根据返回结果执行跳转,这种方式更灵活:

控制器代码修改:

[HttpDelete("delete")]
public async Task<IActionResult> Delete([FromQuery]string encodedName)
{
    var command = new DeleteProjectCommand() { EncodedName = encodedName};
    await _mediator.Send(command);
    this.SetNotification("success", $"Project has been deleted");

    // 返回包含跳转地址的JSON
    return Json(new { 
        Success = true, 
        RedirectUrl = Url.Action(nameof(Index)) 
    });
}

前端代码修改:

$('#deleteButton').click(function (event) {
    event.preventDefault();
    const encodedName = $(this).data('encodedname');
    $.ajax({
        url: `/projects/delete?encodedName=${encodeURIComponent(encodedName)}`,
        type: 'DELETE',
        success: function (response) {
            if (response.Success) {
                toastr["success"]("Deleted project");
                window.location.href = response.RedirectUrl;
            }
        },
        error: function () {
            toastr["error"]("Something went wrong");
        }
    });
});
额外提示
  • 务必移除async: false,同步Ajax请求会导致浏览器在请求期间卡顿,完全不符合现代Web应用的交互体验。
  • 后端的SetNotification如果是基于Session的通知,跳转后需要确保Index页面能正确读取并显示这个通知。

内容的提问来源于stack exchange,提问作者luhmÿpickle

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 21:43:30