Asp .Net MVC - SPLessons

ASP.Net MVC ViewBag

Home > Lesson > Chapter 8
SPLessons 5 Steps, 3 Clicks
5 Steps - 3 Clicks

ASP.Net MVC ViewBag

ASP.Net MVC ViewBag

shape Description

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.

shape Step-1

Open the Visual Studio 2013(or the version whatever you have) and create an MVC Application.

shape 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.

shape 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]

shape Step-4

Now, Goto Solution Explorer View Home and then double click on the About.cshtml as shown in the below figure.

shape 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]

shape 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.

shape Step-6

Press F5 to run the Application. Then, the output will be displayed in the browser.

shape Step-7

Type the following URL in the Address bar to get our View.
  • Then, the output will be displayed in the browser as shown in the below figure.