In this article I will explain with an example, how to populate (bind) MVC6 Grid using
ADO.Net in
ASP.Net Core (.Net Core 8)
MVC.
MVC6 Grid for ASP.Net Core
This article makes use of
MVC6 Grid library for implementing
WebGrid, as it is not available by default in .Net
Core.
Database
Here I am making use of Microsoft’s Northwind Database. You can download it from here.
Namespaces
You will need to import the following namespaces.
using System.Data;
using System.Data.SqlClient;
Controller
The Controller consists of the following Action method.
Action method for handling GET operation
Inside this Action method, the Top 10 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
{
public IActionResult Index()
{
string constr = @"Data Source=.\SQL2019;Initial Catalog=Northwind;uid=sa;pwd=pass@123;TrustServerCertificate=True";
using (SqlConnection con = new SqlConnection(constr))
{
string query = "SELECT TOP 10 CustomerID, ContactName, City, Country FROM Customers";
using (SqlCommand cmd = new SqlCommand(query, con))
{
using (SqlDataAdapter sda = new SqlDataAdapter(cmd))
{
using (DataSet ds = new DataSet())
{
sda.Fill(ds);
return View(ds);
}
}
}
}
}
}
View
HTML Markup
Inside the View, in the very first line
DataSet is declared as Model for the View.
The System.Data, NonFactors.Mvc.Grid namespaces and mvc-grid.css file are inherited inside the View.
The
DataTable is passed to the
Grid function of the
MVC6 Grid HTML Helper class.
The columns have been added using the
Build method of the
MVC6 Grid HTML Helper class.
Inside the
Build method of the
MVC6 Grid HTML Helper class, a foreach loop will be executed over the Columns.
Inside the loop, dynamically columns have been added using the Add method and the Header Text of the column is set using the Titled function by passing the Column Name.
@model DataSet
@using System.Data;
@using NonFactors.Mvc.Grid;
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link href="~/css/mvc-grid/mvc-grid.css" rel="stylesheet" />
</head>
<body>
<div style="width: 550px">
@(Html.Grid(Model.Tables[0].Rows.Cast<DataRow>())
.Build(columns =>
{
foreach (DataColumn column in Model.Tables[0].Columns)
{
columns.Add(model => model[column.ColumnName]).Titled(column.ColumnName);
}
})
)
</div>
</body>
</html>
Screenshot
Downloads