Pass DataTable from Controller to View in ASP.Net MVC


In this article, you are going to learn how to pass a DataTable from a controller to a razor view in ASP.NET MVC. The table passed will be displayed on the view page.

Pass DataTable from Controller to View

To get started, let’s create a database table like the following:

CREATE TABLE [dbo].[Novel](
[NovelID] [int] NOT NULL,
[Title] [varchar](255) NULL,
[Author] [varchar](255) NULL,
[Price] [decimal](18, 0) NULL,
CONSTRAINT [PK_Novel] PRIMARY KEY CLUSTERED
(
[NovelID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

SET ANSI_PADDING OFF
GO

Then add a few records to that table:

Novel Table

Now add the following namespaces to the controller

using System.Data;
using System.Data.SqlClient;

The controller

Now add the code below to the Index function inside the controller

public ActionResult Index()
    {
        DataTable dt = new DataTable();

        string str = "Data Source=localhost;Initial Catalog=Books;Integrated Security=True";
        using (SqlConnection cn = new SqlConnection(str))
        {
          
            using (SqlCommand cmd = new SqlCommand("SELECT * FROM Novel"))
            {
                cmd.Connection = cn;
                using (SqlDataAdapter da = new SqlDataAdapter(cmd))
                {
                    da.Fill(dt);
                }
            }
        }

        return View(dt);
    }

The View

<h1>Pass DataTable from Controller to View in ASP.Net MVC</h1>

@using System.Data
@model DataTable
 
<table cellpadding="5" cellspacing="5" border="1">
    <tr style="background-color:aliceblue">

        <th>Title</th>
        <th>Author</th>
        <th>Price</th>
    </tr>
    @foreach (DataRow dr in Model.Rows)
    {
        <tr>

            <td>@dr["Title"]</td>
            <td>@dr["Author"]</td>
            <td>@dr["Price"]</td>
        </tr>
    }
</table>

Now run the application

Result

Related Articles

Asha Shoukeir

About Asha shoukeir

Software Developer and System Administrator

View all posts by Asha shoukeir →

Leave a Reply