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;
Razor PageModel (Code-Behind)
The PageModel consists of following Handler method.
Handler method for handling GET operation
Inside this Handler method, the
Top 10 records are fetched from the
Customers Table using
ADO.Net.
The records are inserted into a public property Customers (
DataSet) using
SqlDataAdapter class object.
Finally, the Customers is returned to the Razor Page.
public class IndexModel : PageModel
{
public DataSet Customers { get; set; }
public void OnGet()
{
string constr = @"Data Source=.\SQL2019;Initial Catalog=Northwind;uid=sa;pwd=pass@123";
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())
{
Customers = new DataSet();
sda.Fill(Customers);
}
}
}
}
}
}
Razor Page (HTML)
HTML Markup
Inside the Razor Page, the System.Data, NonFactors.Mvc.Grid namespaces and mvc-grid.css file are inherited.
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.
@page
@model WebGrid_DataTable_DataSet_Razor_Core.Pages.IndexModel
@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.Customers.Tables[0].Rows.Cast<DataRow>())
.Build(columns =>
{
foreach (DataColumn column in Model.Customers.Tables[0].Columns)
{
columns.Add(model => model[column.ColumnName]).Titled(column.ColumnName);
}
})
)
</div>
</body>
</html>
Screenshot
Downloads