问题
I've set a value into Viewbag.message in my default HomeController and successfully display it in my Shared/_Layout.cshtml.
After that I added another TestController and in the TestController view, Viewbag.message seems to be null. May I know what's wrong with it.
Correct me if I'm wrong,from my understanding Viewbag.Message should be available from all over the places?
回答1:
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.
- 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
回答2:
[HttpPost]
public ActionResult Index()
{
TempData["Message"] = "Success";
return RedirectToAction("Index");
}
public ActionResult Index()
{
ViewBag.Message=TempData["Message"];
return View();
}
回答3:
//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();
}
来源:https://stackoverflow.com/questions/18479297/mvc-passing-viewbag-value-from-another-controller