c# - 无法显示 ViewBag 中的值

标签 c# asp.net-core model-view-controller asp.net-core-mvc viewbag

我试图在我的 .cshtml 页面上显示 ViewBag 的值,但该值始终为空。下面是我的代码:

public async Task<IActionResult> DateCalc( int? department)
{

    ViewBag.DestroyCount = 4; // docDestroyed;
    return RedirectToAction(nameof(Index));
}

这是我的 Index.cshtml 中的内容:

<div class="card">
    <form asp-action="DateCalc" enctype="multipart/form-data">
  <h5 class="card-header">Documents destroyed by section</h5>
  <div class="card-body">
       <div class="left">
        <label>Select Department(s)</label>
           @Html.DropDownList("department", (IEnumerable
        <SelectListItem>)ViewBag.department, new{@class="form-control"})
       </div>
       <div></div>

   <br /><br />
    <input type="submit" value="submit" class="btn btn-primary" />
    <p class="card-text">Documents Destroyed by Section: </p>@Html.Label((string)ViewBag.DestroyCount) 
  </div>
  </form>
</div>

当我点击提交按钮时,我希望“按部分销毁的文档:”显示 4,但它不显示任何内容。

这是我在单击提交按钮后尝试显示 DestroyCount 的行:

@Html.Label((string)ViewBag.DestroyCount) 

任何帮助将不胜感激。

最佳答案

ViewBag.DestroyCount的数据当您执行重定向时丢失:

public async Task<IActionResult> DateCalc(int? department)
{
    ...
    return RedirectToAction(nameof(Index));
}

ViewBag的数据和ViewData仅在同一请求内持续。

根据这个table ,

<表类=“s-表”> <标题> 查看包 查看数据 临时数据 <正文> 如果发生重定向,其值将变为 null。 与ViewData相同 TempData 用于在两个连续请求之间传递数据。 它仅在当前请求期间存在。 与ViewData相同 TempData 仅在当前和后续请求期间有效

解决方案 1:使用 TempData

您需要一个TempData在请求之间传递数据。

Controller

public async Task<IActionResult> DateCalc(int? department)
{
    TempData["DestroyCount"] = 4; // docDestroyed;
    return RedirectToAction(nameof(Index));
}

View

@Html.Label(TempData["DestroyCount"]?.ToString())

Demo

enter image description here


解决方案2:返回View但不返回RedirectToAction

另一种方法是返回 View()而不是RedirectToAction()ViewBag的数据可用,因为它位于同一请求中并且没有重定向。

但是,请确保您需要初始化 ViewBag.department在返回索引 View 之前,我在 InitIndex 中编写了实现方法,并且此方法为 Index 共享和DateCalc行动方法。

Controller

public IActionResult Index()
{
    InitIndex();

    return View();
}

public async Task<IActionResult> DateCalc(int? department)
{
    ViewBag.DestroyCount = 4; // docDestroyed;
    InitIndex();

    return View(nameof(Index));
}

View

@Html.Label(((int?)ViewBag.DestroyCount)?.ToString())

注意浏览器 URL 将更改为“/{controller}/DateCalc”。

Demo

enter image description here

关于c# - 无法显示 ViewBag 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73256536/

相关文章:

c# - httpclient PostAsJsonAsync方法未找到.net框架4并行解决方案

c# - 如何比较一本字典的值?

c# - 交换文件中的字节

asp.net-mvc - 在与 Azure AD B2C 集成的网站中获取访问 token

UseCookieAuthentication 中的 ASP.NET Core Web 应用程序 ExpireTimeSpan 不起作用

asp.net-core - Serilog 未记录到控制台

C# MVC 通过 JQuery AJAX 发送对象

java - MVC 井字游戏

php - 没有紧凑结构的 MVC 应用程序的原因是什么?

c# - RSA 加密 - 使用私钥加密