繁体   English   中英

MVC 5 asp.net,从控制器到视图的viewbag无法正常工作

[英]MVC 5 asp.net, viewbag from controller to view is not working

这是控制器

public ActionResult Test() {

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

} 

在Action Named Details视图中 ,我将检查它是否有ViewBag来显示和显示它:

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

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

谢谢

基本上你正在做的是从你的Index方法调用方法Details ,因为你已经用id重载了你的Details动作,所以也传递消息:

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

然后在Details视图中,您可以像这样访问该属性:

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM