MVC从另一个控制器传递ViewBag值

时间:2013-08-28 04:08:17

标签: asp.net-mvc asp.net-mvc-4 viewbag

我已在默认的HomeController中将值设置为Viewbag.message,并在我的Shared/_Layout.cshtml中成功显示。

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

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

3 个答案:

答案 0 :(得分:25)

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

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

下面是一个汇总表,显示了不同的持久性机制。 Summary of ViewBag and the other mechanism Credit:CodeProjectArticle

答案 1 :(得分:6)

[HttpPost]
public ActionResult Index()
{
    TempData["Message"] = "Success";
    return RedirectToAction("Index");
}


public ActionResult Index()
{
    ViewBag.Message=TempData["Message"];
    return View();
}

答案 2 :(得分:0)

//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();
}
相关问题