MVC Transfer ViewBag value from another controller

I set the value in Viewbag.message in my HomeController by default and successfully displayed it in my Shared/_Layout.cshtml .

After that I added another TestController and in the ViewController Viewbag.message seems to be null. May I find out what is wrong with him.

Correct me if I am mistaken, from my understanding of Viewbag.message should be accessible from all corners?

+4
source share
3 answers

ViewBag is a dynamic property that takes advantage of the new dynamic features in C # 4.0. This is mainly a wrapper around ViewData, and is also used to transfer data from the controller to the corresponding view.

  • His life also lies only during the current request. If the redirection occurs, then its value becomes zero.
  • To create complex data types, typecasting is not required.

The following is a summary table that shows another save mechanism. Summary of ViewBag and the other mechanism Credit: CodeProject article

+20
source
 [HttpPost] public ActionResult Index() { TempData["Message"] = "Success"; return RedirectToAction("Index"); } public ActionResult Index() { VieBag.Message=TempData["Message"]; return View(); } 
+5
source
 //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(); } 
0
source

Source: https://habr.com/ru/post/1499293/


All Articles