Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Passing ViewBag value from another controller

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?

like image 406
SuicideSheep Avatar asked Aug 28 '13 04:08

SuicideSheep


People also ask

How pass ViewBag value from view to controller in MVC?

To pass the strongly typed data from Controller to View using ViewBag, we have to make a model class then populate its properties with some data and then pass that data to ViewBag with the help of a property. And then in the View, we can access the data of model class by using ViewBag with the pre-defined property.

How we can pass data from one controller to another controller in MVC?

ViewData, ViewBag, and TempData are used to pass data between controller, action, and views. To pass data from the controller to view, either ViewData or ViewBag can be used. To pass data from one controller to another controller, TempData can be used.

Can we pass data from view to controller using ViewBag?

Yes you cannot pass a Viewbag from view to controller. But you can pass them using TempData. Add this to your View. But this TempData passes the information as an object.

How do you pass value from one Cshtml to another Cshtml?

The data from the Source cshtml page (View) will be posted (submitted) using Form Post to the Controller's Action method of the Destination cshtml page (View). Then finally, the received data will be displayed in the Destination cshtml page (View) using ViewBag.


2 Answers

[HttpPost]
public ActionResult Index()
{
    TempData["Message"] = "Success";
    return RedirectToAction("Index");
}


public ActionResult Index()
{
    ViewBag.Message=TempData["Message"];
    return View();
}
like image 88
Anjana Avatar answered Sep 23 '22 01:09

Anjana


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 mechanismCredit:CodeProjectArticle

like image 20
Ravi Gadag Avatar answered Sep 22 '22 01:09

Ravi Gadag