MVC 5 asp.net,viewbag从控制器向视图不工作(MVC 5 asp.net, vie

2019-09-27 17:37发布

这是控制器

public ActionResult Test() {

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

} 

在行动命名详细 视图我会检查其是否具有ViewBag显示,并显示它:

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

但这里的重定向工作正常的页面,它不显示我已经存储在ViewBag.TheMessageIs消息

谢谢

Answer 1:

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();
}

你必须像这样做,因为当你重定向到另一个活动/鉴于viewbag失去其价值



Answer 2:

基本上你正在做的是调用方法DetailsIndex法,因为你已经有超载的详细操作id ,它传递的讯息:

public ActionResult Index()
{
    //ViewBag.TheMessageIs = "this is the message";
    return RedirectToAction("Details", new { id = 1, TheMessageIs = "this is the message" });
}

public ActionResult Details(int id, string TheMessageIs)
{
    ViewBag.TheMessageIs = TheMessageIs;
    return View();
}

然后在详细查看您可以访问属性是这样的:

@ViewBag.TheMessageIs


文章来源: MVC 5 asp.net, viewbag from controller to view is not working