12

我已经Viewbag.message在我的默认 HomeController 中设置了一个值,并成功地将它显示在我的Shared/_Layout.cshtml.

之后我添加了另一个 TestController 并在 TestController 视图中,Viewbag.message似乎为空。我可以知道它有什么问题吗?

如果我错了,请纠正我,根据我的理解Viewbag.Message应该可以从各地获得?

4

3 回答 3

35

ViewBag 是一个动态属性,它利用了 C# 4.0 中的新动态特性。基本上它是 ViewData 的包装器,也用于将数据从控制器传递到相应的视图。

  • 它的生命也只存在于当前的请求中。如果发生重定向,则它的值变为空。
  • 它不需要对复杂数据类型进行类型转换。

下面是一个汇总表,显示了不同的持久性机制。 ViewBag 及其他机制总结 信用:代码项目文章

于 2013-08-28T04:14:07.300 回答
11
[HttpPost]
public ActionResult Index()
{
    TempData["Message"] = "Success";
    return RedirectToAction("Index");
}


public ActionResult Index()
{
    ViewBag.Message=TempData["Message"];
    return View();
}
于 2015-10-29T09:57:25.447 回答
-1
//one controller to another controller you need to use seesion 
//this is Home controller

[httpPost]
public actionresult Index()
{
    session["Message"] = "Welcome to session tutorial";
    return redirectToAction("Index","About");
}

//now pass to the another About controller

[httpPost]
public actionresult About()
{
    Viewbag.Message = session["Message"]
    return view();
}
于 2017-07-20T07:15:51.120 回答