Reputation: 822
I am in ASP.NET MVC, and I am currently using ADO.NET to query my database, fill a DataTable, then passing the DataTable to my view to display the data on the screen. (I am purposely not following MVC best practices, im just trying to figure out a concept)
public ActionResult Index()
{
DataTable dt = new DataTable();
using (AdomdConnection con = new AdomdConnection(consString))
{
con.Open();
AdomdCommand query = new AdomdCommand("Some query blah blah", con);
AdomdDataAdapter da = new AdomdDataAdapter(query);
da.Fill(dt);
}
return View(dt);
}
And in the View
@model System.Data.DataTable
@{
ViewBag.Title = "Home Page";
}
<table id="infoTable">
<thead>
<tr>
<th>Key</th>
<th>Weight</th>
<th>Discount Amount</th>
<th>Sales Count</th>
</tr>
</thead>
@foreach(System.Data.DataRow row in Model.Rows)
{
<tr>
@foreach(var cell in row.ItemArray)
{
<td>@cell</td>
}
</tr>
}
</table>
This currently displays all the data rows on my screen. I want to add Pagination, so that only a few records will display on the screen at a time, and uses a control at the bottom of the table to view more records.
I have found PagedList, and the concept seems like it would work well. Instead of passing my DataTable to my view, I want to pass a PagedList, but I am not sure how to convert my DataTable to a PagedList.
Does anyone know how I can take my DataTable, make it into a PagedList, then pass the PagedList to my view for Pagination?
Upvotes: 1
Views: 4793
Reputation: 822
First I separated my DataTable into its own Model as it should be, then in this model,
I created
public List<DataRow> list { get; set;}//Regular list to hold data from Datatable
public PagedList<DataRow> plist { get; set; }//Paged list for pagination to be filled with data from regular List
I then casted my DataTable to a List
list = dt.AsEnumerable().ToList();
Then I initialized my PagedList using my List
plist = new PagedList<DataRow>(list, page ?? 1, 5);
I was then able to pass this Model to my View, with the ability to iterate through my PagedList
plist
Upvotes: 1