ViewBag Sample in MVC: Day 2

Introduction

This article describes ViewBag in MVC.

A ViewBag is used to share values from the controller to the view. A ViewBag has no predefined properties, but we can define a desired property by adding them to the property.

Step 1

Click on the "Start" Button -> Expand "Visual Studio 2013" -> Click on "Visual Studio 2013".

Go to "File" Menu -> Expand "New" -> Click on "Project".

Select "Visual C#" under "Web" -> Select "ASP.NET Web Application" in the center.

Name the project -> select your desired location.

Select "Empty" template -> Check "MVC" from "Add folders and core references for:".

Right-click on "Controllers" and select "Add -> Controller".

Controller

Step 2

Select "MVC 5 Controller - Empty" to add an empty controller.

Click on the "Add" button.

add empty controller

Step 3

Name the controller.

Name the controller

Step 4

Here we create a "name" property for the ViewBag and set the value of the current datetime.

set value of current datetime

Step 5

Now we need to create a view.

Right-click on "Index" and select "Add View".

Add View

Step 6

Name the view and select "Empty (without model)" as the template. Click on the "Add" button.

Add button

Step 7

Refer to the following code snippet to get the value from the ViewBag.

get value from ViewBag

Step 8

Run the project and you will get the current datetime on the browser using the ViewBag.

Run the project

<< Day 1                   >> Day 3


Similar Articles