Datatable in ViewData Sample in MVC

Datatable in ViewData Sample in MVC

Introduction

This article describes how to pass an entire datatable from controller to view.

Step 1

Create a MVC project with "Empty" template.

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

In the MVC architecture, a view can work on the model passed by the controller. So here we pass our model via ViewData.Model.

Create an object of the datatable.

Feed some data in datatable, here we store factoryclasses in the datatable.

Assign the datatable to ViewData.Model.

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

In the View, we can get the Model passed by the controller. We can get the data from ViewData.Model using a foreach loop.

Please refer to the following code snippet.

image.png

Step 8

Run the project and you get each row of the datatable in the browser using ViewData.

image.png

<< Day 2

>> Day 3