In this article I will explain with an example, how to bind DataTable to View in ASP.Net MVC Razor.
Though it is not a good practice to use DataSets and DataTables as Model in MVC architecture, hence user’s please make a note that this is just an informative article and does not recommend to use DataSets and DataTables in ASP.Net MVC Razor.
Note: For beginners in ASP.Net MVC, please refer my article ASP.Net MVC Hello World Tutorial with Sample Program example.
 
 
Database
I have made use of the following table Customers with the schema as follows. CustomerId is an Auto-Increment (Identity) column.
MVC View DataTable example: Bind DataTable to View in ASP.Net MVC
 
I have already inserted few records in the table.
MVC View DataTable example: Bind DataTable to View in ASP.Net MVC
 
Note: You can download the database table SQL by clicking the download link below.
          Download SQL file
 
 
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 DataSet using SqlDataAdapter class object. Finally the DataSet is returned to the View.
public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        DataSet ds = new DataSet();
        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(ds);
                }
            }
        }
 
        return View(ds);
    }
}
 
 
View
Inside the View, the DataSet class is declared as Model for the View. For displaying the records, an HTML Table is used. A loop will be executed over the rows of the DataTable which will generate the HTML Table rows with the Customer records.
@using System.Data
@model DataSet
@{
    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>ContactName</th>
            <th>Country</th>
        </tr>
        @foreach (DataRow row in Model.Tables[0].Rows)
        {
            <tr>
                <td>@row["CustomerId"]</td>
                <td>@row["Name"]</td>
                <td>@row["Country"]</td>
            </tr>
        }
    </table>
</body>
</html>
 
 
Screenshots
MVC View DataTable example: Bind DataTable to View in ASP.Net MVC
 
 
Downloads