MVC 5 asp.net,从控制器到视图的视图包不起作用

MVC 5 asp.net,从控制器到视图的视图包不起作用

问题描述:

这是控制器

public ActionResult Test() {

@ViewBag.TheMessageIs = "this is the message";
return RedirectToAction("Details", new { id = theId});

} 

在名为详细信息的操作的视图上,我将检查它是否具有要显示的ViewBag并将其显示:

on the view of Action Named Details I will check if it has the ViewBag to show and show it:

@{
  if(ViewBag.TheMessageIs != null){
         @ViewBag.TheMessageIs
  }
}

但是这里重定向到页面工作正常,它没有显示我存储在ViewBag.TheMessageIs中的消息

but here the redirection is working fine to the page, it's not show the message I have stored in ViewBag.TheMessageIs

谢谢

public ActionResult Test() {
 TempData["shortMessage"] = "MyMessage";
 return RedirectToAction("Details", new { id = theId});
}

public ActionResult Details {
 //now I can populate my ViewBag (if I want to) with the TempData["shortMessage"] content
  ViewBag.TheMessageIs = TempData["shortMessage"].ToString();
  return View();
}

您必须这样做,因为当您重定向到另一个活动/视图时,视图包会失去其值

You have to do it like this since the viewbag looses its value when you redirect to another active / view