ViewBag Sample in MVC

ViewBag Sample in MVC

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

image.png

Step 2

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

Click on the "Add" button.

image.png

Step 3

Name the controller.

image.png

Step 4

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

image.png

Step 5

Now we need to create a view.

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

image.png

Step 6

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

image.png

Step 7

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

image.png

Step 8

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

image.png

<< Day 1

>> Day 3