MVC: Using ViewBag for Data Storage

Please see my other MVC articles.

Passing data to a View.

Sometimes a business requirement necessitates data to passed from a Controller to the View for displaying to the user.
One method MVC provides is the object ViewBag which allows you to easily attach inference-typed variables for initialing with many types of data.

To illustrate this feature, I first created a very simple controller and generic action method which constructs a message welcome users to my site along with the current date and time.
The variable “Greeting,” is a completely arbitrary name I’ve decided to use that is easy to remember later when I’m in the View.


With my Controller created, now I’ll create the View to display my welcome message.
In order to retrieve my message, all I need to do is call the ViewBag object, then its Greeting variable.


To see my example message, I’ll add a simple HTML link to my homepage which allows me to execute my controller.




Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s