asp.net-mvc MVC 从另一个控制器传递 ViewBag 值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18479297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
MVC Passing ViewBag value from another controller
提问by SuicideSheep
I've set a value into Viewbag.messagein my default HomeController and successfully display it in my Shared/_Layout.cshtml.
我已经Viewbag.message在我的默认 HomeController 中设置了一个值,并成功地将它显示在我的Shared/_Layout.cshtml.
After that I added another TestController and in the TestController view, Viewbag.messageseems to be null. May I know what's wrong with it.
之后我添加了另一个 TestController 并且在 TestController 视图中,Viewbag.message似乎为空。我可以知道它有什么问题吗。
Correct me if I'm wrong,from my understanding Viewbag.Messageshould be available from all over the places?
如果我错了,请纠正我,根据我的理解Viewbag.Message应该可以从所有地方获得?
回答by Ravi Gadag
ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0. Basically it is a wrapper around the ViewData and also used to pass data from controller to corresponding view.
ViewBag 是一个动态属性,它利用了 C# 4.0 中的新动态特性。基本上它是 ViewData 的包装器,也用于将数据从控制器传递到相应的视图。
- It's life also lies only during the current request. If redirection occurs then it's value becomes null.
- It doesn't required typecasting for complex data type.
- 它的生命也只存在于当前请求期间。如果发生重定向,则它的值变为空。
- 它不需要对复杂数据类型进行类型转换。
Below is a summary table which shows different mechanism of persistence.
Credit:CodeProjectArticle
下面是一个汇总表,显示了不同的持久性机制。
信用:代码项目文章
回答by Anjana
[HttpPost]
public ActionResult Index()
{
TempData["Message"] = "Success";
return RedirectToAction("Index");
}
public ActionResult Index()
{
ViewBag.Message=TempData["Message"];
return View();
}
回答by saurav singh
//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();
}

