MVC Passing ViewBag value from another controller

SuicideSheep picture SuicideSheep · Aug 28, 2013 · Viewed 25.7k times · Source

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?

Answer

Ravi Gadag picture Ravi Gadag · Aug 28, 2013

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. Summary of ViewBag and the other mechanism Credit:CodeProjectArticle