ViewData Samples in MVC: Day 1

Introduction

This series contains step-by-step MVC samples for absolute beginners. It covers only the practical implementations of MVC concepts.

Let's start with the viewdata. Viewdata maintains data when you move from a controller to a view.

Step 1

Click on the "Start" Button then expand "Visual Studio 2013" and click on "Visual Studio 2013".

Visual Studio

It will open the Start Page of "Visual Studio 2013".

Step 2

Go to the "File" menu then expand "New" and click on "Project…".

Menu

Step 3

Select "Visual C#" on the left and then select "Web" and select "ASP.NET Web Application" on the center then name the project and select your desired location.

Visual C#

Step 4

Select the "Empty" template then check "MVC" from "Add folders and core references for:".

MVC

Step 5

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

Controllers

Step 6

Select "MVC 5 Controller - Empty" to add an empty controller then click on the "Add" button.

MVC 5 Controller

Step 7

Name the controller.

Name the controller

Step 8

This will add an empty controller inside the "Controllers" folder. The Controller has one Action method and action methods typically return a result that is known as an "ActionResult". ActionResult represents a result of an action method. Here the action result returns a View method.

To pass the value from the controller to the view we need to store a value in the ViewData inside the controller. Here we store a datetime value in the ViewData. Find the syntax of viewdata in the following screen.

datetime value

Step 9

Now we need to create a view. Right-click on "Index" and select "Add View…".

Add View

Step 10

For now do not change the view name. The Action method name and view name should be the same. Select "Empty (without model)" as the template and click on the "Add" button.

Empty

Step 11

The Index.cshtml file is created under the Views >> Home. We are using the view-engine option called "Razor". So we use rezor's @ and then syntax to get data from ViewData.

Please refer to the following screen shot for the entire syntax.

Home

Step 12

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

datetime
ViewData is one of the ways to transfer data from a controller to a view.

>> Day 2