atiyar
atiyar

Reputation: 8338

How exactly does a View access ViewBag data stored by a Controller?

I'm new to ASP.NET MVC. Just started learning. All the tutorials, articles or books I'm following say something like "you can send data from Controller to a View using the ViewBag..."

From the Controller -

public ActionResult Index()
{
    ViewBag.Message = "Index Message";
    return View();
}

to the View -

<h3>@ViewBag.Message</h3>

But, what nobody cares to explain, and what I'm having hard time understanding is how does (or can) the View access this ViewBag data sent from the Controller?

What I know,

  1. under the hood ViewBag is of type ViewDataDictionary
  2. the ViewBag in the Controller is from the ViewBag property of the ControllerBase class
  3. the ViewBag in the View is from the ViewBag property of the WebViewPage class

And from what I understand,

So what I don't understand,

Upvotes: 0

Views: 902

Answers (1)

Andy T
Andy T

Reputation: 9881

Take a look at the source code for the Controller class.

There you will see:

protected internal virtual ViewResult View(string viewName, string masterName, object model)

Which is what is called when you call return View(). That method creates an ActionResult and passes the ViewData from controller. So, yes, they both share the same instance of the dictionary object.

Upvotes: 1

Related Questions