我试图在我的 .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 ,
解决方案 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
解决方案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
关于c# - 无法显示 ViewBag 中的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73256536/