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

ASP.NET跳转Index页面后ViewBag提示信息不显示问题求助

解决ASP.NET中RedirectToAction后ViewBag提示无法显示的问题

在ASP.NET中开发Portfolio分类创建功能时,成功创建数据后通过RedirectToAction("Index")跳转至列表页,但设置的ViewBag成功/错误提示无法在Index页面显示,仅能看到硬编码内容。

问题根源

ViewBag的生命周期仅局限于当前HTTP请求,当执行RedirectToAction时,浏览器会发起全新的HTTP请求,原请求中的ViewBag数据会被销毁,因此新请求对应的Index页面无法获取到之前设置的提示信息。

解决方案:使用TempData跨请求传递数据

TempData专门用于跨请求场景下传递临时数据(默认基于Session实现,也可配置为Cookie模式),能完美解决跳转后提示信息丢失的问题。

1. 修改控制器代码

将原有的ViewBag替换为TempData:

public async Task<IActionResult> CreatePortfolioCategory(CreatePortfolioCategoryViewModel createPortfolioCategoryViewModel)
{
    if (!ModelState.IsValid)
    {
        return View(createPortfolioCategoryViewModel);
    }

    var result = await _siteService.CreatePortfolioCategory(createPortfolioCategoryViewModel);
    switch (result)
    {
        case CreatePortfolioCategoryResult.NotFound:
            TempData["ErrorText"] = "Error";
            return View(createPortfolioCategoryViewModel);

        case CreatePortfolioCategoryResult.Created:
            TempData["SuccessText"] = "Successful Create";
            break;
    }
    return RedirectToAction("Index");
}

2. 修改Index视图代码

读取TempData中的提示信息并渲染:

<div>
@if (!string.IsNullOrEmpty(TempData["ErrorText"] as string))
{
    <div class="alert alert-danger">
        <p>@TempData["ErrorText"]</p>
    </div>
}

@if (!string.IsNullOrEmpty(TempData["SuccessText"] as string))
{
    <div class="alert alert-success">
        <p>@TempData["SuccessText"]</p>
    </div>
}
</div>

<h2>Successfull</h2>

补充说明

  • TempData中的数据默认会在读取后自动标记为删除,若需要在后续请求中继续保留数据,可在读取后调用TempData.Keep("KeyName")方法。
  • 若项目禁用了Session,可配置TempData使用Cookie存储(需在Startup中配置services.Configure<CookieTempDataProviderOptions>(options => ...))。

内容的提问来源于stack exchange,提问作者Hasti Asadi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 10:35:20