MVC Passing ViewBag value from another controller
Asked Answered
Q

3

16

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?

Quarterdeck answered 28/8, 2013 at 4:8 Comment(1)
for that TestController view also you have to what you have done for Viewbag.message in my default HomeControllerWetmore
P
38

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

Pleopod answered 28/8, 2013 at 4:14 Comment(1)
using TempData.Keep will maintain the data from View to Controller and Controller to View.Complement
C
13
[HttpPost]
public ActionResult Index()
{
    TempData["Message"] = "Success";
    return RedirectToAction("Index");
}


public ActionResult Index()
{
    ViewBag.Message=TempData["Message"];
    return View();
}
Coral answered 29/10, 2015 at 9:57 Comment(1)
As a side-note: The SessionStateTempDataProvider class requires session state to be enabled.Golanka
C
-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();
}
Celeski answered 20/7, 2017 at 7:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.