In this article I will explain with an example, how to pass (send) DataTable from Controller to View in ASP.Net MVC Razor.
The DataTable will be populated from Database using ADO.Net inside the Controller and it will be passed to the View as Model.
Later in View, the DataTable will be iterated and the data will be displayed with the help of HTML Table in ASP.Net MVC Razor.
Database
I have made use of the following table Customers with the schema as follows. CustomerId is an Auto-Increment (Identity) column.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
Namespaces
You will need to import the following namespaces.
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
Controller
The Controller consists of the Index Action method. Inside this Action method, the records are fetched from the Customers Table using ADO.Net.
The records are inserted into a DataTable using SqlDataAdapter class object. Finally the DataTable is returned to the View.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
DataTable dt = new DataTable();
string constr = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = "SELECT * FROM Customers";
using (SqlCommand cmd = new SqlCommand(query))
{
cmd.Connection = con;
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
sda.Fill(dt);
}
}
}
return View(dt);
}
}
View
Inside the View, the DataTable class is declared as Model for the View. For displaying the records, an HTML Table is used. A loop (iteration) will be executed over the rows of the DataTable which will generate the HTML Table rows with the Customer records.
@using System.Data
@model DataTable
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
</head>
<body>
<table cellpadding="0" cellspacing="0">
<tr>
<th>CustomerId</th>
<th>Name</th>
<th>Country</th>
</tr>
@foreach (DataRow row in Model.Rows)
{
<tr>
<td>@row["CustomerId"]</td>
<td>@row["Name"]</td>
<td>@row["Country"]</td>
</tr>
}
</table>
</body>
</html>
Screenshot
Downloads