View Bag is a dynamic object where any properties can be added dynamically.
For Example,if one want to pass some contact information like Name and Contact Number to the view named as UserInformation from the HomeController, view bag can be used.
Follow the below steps to implement above requirement.
Step-1
Open the Visual Studio 2013(or the version whatever you have) and create an MVC Application.
Step-2
Now, Goto Solution Explorer. Double click on the HomeController under the Controller folder as shown in the below figure.
Then, the HomeController.cshtml will be opened.
Step-3
Write the following code under the Action method About.
[csharp]
public ActionResult About()
{
ViewBag.contactperson = "James Gosley";
ViewBag.contactnumber = "935232623";
return View();
}
[/csharp]
Step-4
Now, Goto Solution Explorer ViewHome and then double click on the About.cshtml as shown in the below figure.
Step-5
Write the following code in the About.cshtml.
[html]
@{
ViewBag.Title = "About";
}
<h2>About</h2>
<div>
<h4>
Contact Person:@ViewBag.contactperson;
Contatc Number:@ViewBag.contactnumber;
</h4>
</div>
[/html]
Step-5
Change the RouteConfig.cs as follows.
Go to Solution Explorer ->App_Start folder and then double click on the RouteConfig.cs.
Now, Change the Action Name shown in the below figure.
Step-6
Press F5 to run the Application. Then, the output will be displayed in the browser.
Step-7
Type the following URL in the Address bar to get our View.
URL
http://localhost:9661/Home/About
Then, the output will be displayed in the browser as shown in the below figure.