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

ASP.NET Core中从Edit页面带参数RedirectToAction返回Index页面

解决ASP.NET Core MVC编辑后返回原页码Index页面的问题

要实现编辑完成后返回之前的Index页面(而非默认第1页),核心是将页码从Index页面传递到Edit的POST控制器,具体步骤如下:

1. 给Edit的GET方法添加页码参数并传递到视图

修改POesController中的Edit GET方法,接收来自Index页面的页码参数,并将其存入ViewBag供视图使用:

public async Task<IActionResult> Edit(int id, int pg = 1)
{
    var pO = await _context.POT.FindAsync(id);
    if (pO == null)
    {
        return NotFound();
    }
    ViewBag.CurrentPage = pg;
    return View(pO);
}

2. 在Edit视图中添加隐藏字段保存页码

在Edit页面的表单内添加隐藏输入框,确保提交表单时页码参数能传递到POST控制器:

<form asp-action="Edit">
    <!-- 现有表单字段保持不变 -->
    <input type="hidden" name="pg" value="@ViewBag.CurrentPage" />
    <button type="submit" class="btn btn-primary">保存</button>
</form>

3. 修改POST版Edit方法接收页码并重定向

在POST的Edit方法中添加页码参数,保存完成后重定向到对应页码的Index页面:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Edit(int id, int pg = 1, [Bind("Id,Supplier,Description,DateTimeItemReleased,Employee,Additional")] PO pO)
{
    if (id != pO.Id)
    {
        return NotFound();
    }

    if (ModelState.IsValid)
    {
        try
        {
            _context.Update(pO);
            await _context.SaveChangesAsync();
        }
        catch (DbUpdateConcurrencyException)
        {
            if (!POExists(pO.Id))
            {
                return NotFound();
            }
            else
            {
                throw;
            }
        }
        // 重定向到原页码的Index页面
        return RedirectToAction(nameof(Index), new { pg = pg });
    }
    // 验证失败时,重新传递页码到视图
    ViewBag.CurrentPage = pg;
    return View(pO);
}

补充:修改Index页面的编辑链接

确保从Index页面跳转到Edit时携带当前页码,比如Index视图中的编辑按钮:

<a asp-action="Edit" asp-route-id="@item.Id" asp-route-pg="@ViewBag.Pager.CurrentPage">编辑</a>

整个流程:从Index第N页点击编辑→进入Edit页面时携带页码N→提交编辑后,重定向回Index的第N页。

内容的提问来源于stack exchange,提问作者John Bruce

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 10:17:28