15

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?

SuicideSheep
  • 5,260
  • 19
  • 64
  • 117
  • for that TestController view also you have to what you have done for Viewbag.message in my default HomeController – backtrack Aug 28 '13 at 04:13

3 Answers3

37

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

Ravi Gadag
  • 15,735
  • 5
  • 57
  • 83
13
[HttpPost]
public ActionResult Index()
{
    TempData["Message"] = "Success";
    return RedirectToAction("Index");
}


public ActionResult Index()
{
    ViewBag.Message=TempData["Message"];
    return View();
}
GregD
  • 6,860
  • 5
  • 34
  • 61
Anjana
  • 131
  • 1
  • 4
-2
//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();
}
saurav singh
  • 438
  • 6
  • 16