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?
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.
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.
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.
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.
[HttpPost]
public ActionResult Index()
{
TempData["Message"] = "Success";
return RedirectToAction("Index");
}
public ActionResult Index()
{
ViewBag.Message=TempData["Message"];
return View();
}
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.
Below is a summary table which shows different mechanism of persistence. Credit:CodeProjectArticle
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With