Skip to main content

Bootstrap Server Side Pagination - alternative to data tables

Background

Most of the Web developers are familiar with the Datatable.Net for pagination. DataTables can integrate seamlessly with Bootstrap using Bootstrap's table styling options to present a consistent interface with your Bootstrap driven site / app. The main disadvantage with Data table.net is it is applying the pagination at the client side and for the large data set it can take minutes to load the data. Like every other designer I also faced the problem with Data table.net. So what is the best option to replace the client side paging and searching. So I forced to create a custom module to do the pagination and searching. The below sample don’t support the sorting, but got an option to extend the functionality. Please check my Next Post for sorting functionality
The technologies used include, MVC 4.0, HTML5, Bootstarp.css, Knockout. js, Ajax, Web Api 2.0, Linq to SQL and C#.

Knockout.js Model’s

Filter Model

var filter = function () {
var self = this;
self.searchText = ko.observable('');
self.totalCount = ko.observable('0');
self.pageSize = ko.observable('10');
self.currentPageIndex = ko.observable('1');
self.sortBy = ko.observable('');
self.sortAscending = ko.observable(false);
self.countLabel = ko.observable("");
self.enablePrev = ko.observable(true);
self.enableNext = ko.observable(true);
self.totalPageCount = ko.observable('1');
self.individualPageList = ko.observableArray([]);
return self;
}
Adarsh Log Model
var adarshLog = function () {
var self = this;
self.Id = ko.observable('');
self.Name = ko.observable('');
return self;
}
Adarsh Log List Model (Binding both the filter and Adarsh log list)
var adarshLogListModel = function () {
var self = this;
self.adarshLogList = ko.observableArray([]);
self.filterModel = new ko.observable(new filter);
return self;
}

Knockout.js View Model for Adarsh Log

define(['genericContext', 'commonContext', 'logger', 'config', 'model'], function (datacontext, commonContext, logger, config, model) {
var viewModel = function () {
var self = this;
// Search Tip for Search Text Box
self.searchTip = function () {
$('[data-toggle="popover"]').popover()
}
// Help Text

self.searchTipText = ko.observable("Type search keyword....");

// Initialisation
self.adarshLogs = ko.observableArray([]);
self.adarshLogListModel = ko.observable(new model.adarshLogListModel);
self.filter = ko.observable(new model.filter);
self.individualPageList = ko.observableArray([]);

//Getting the records for intital Load
datacontext.getAllPost(self.adarshLogListModel, config.adarshLogUrl, model.adarshLogListModel, self.filter).always(function () {

var list = [];
self.adarshLogListModel().adarshLogList().forEach(function (item) {
var newRecord = new model.adarshLog();
ko.mapping.fromJS(item, {}, newRecord); //map the json into our oversvable object
list.push(newRecord);
});
self.adarshLogs(list);
// var newFilter = model.filter;
ko.mapping.fromJS(self.adarshLogListModel().filterModel(), {}, self.filter());
//(newFilter);
self.individualPageList(self.adarshLogListModel().filterModel().individualPageList());

if (self.filter().currentPageIndex() <= 1) {
self.filter().enablePrev(false);
}
if (self.filter().currentPageIndex() >= self.filter().totalPageCount()) {
self.filter().enableNext(false);
}
self.isBusy(false);

});

// Search fucntionality

self.searchItems = function (selected) {
self.filter().currentPageIndex(1);
datacontext.getAllPost(self.adarshLogListModel, config.adarshLogUrl, model.adarshLogListModel, self.filter).always(function () {
var list = [];
if (self.filter().currentPageIndex() <= 0) {
self.filter().enablePrev(false);
}
self.adarshLogListModel().adarshLogList().forEach(function (item) {
var newRecord = new model.adarshLog();
ko.mapping.fromJS(item, {}, newRecord); //map the json into our oversvable object
list.push(newRecord);
});
self.adarshLogs(list);
// var newFilter = model.filter;
ko.mapping.fromJS(self.adarshLogListModel().filterModel(), {}, self.filter());
//(newFilter);
self.individualPageList(self.adarshLogListModel().filterModel().individualPageList());
if (self.filter().currentPageIndex() <= 1) {
self.filter().enablePrev(false);
}
if (self.filter().currentPageIndex() >= self.filter().totalPageCount()) {
self.filter().enableNext(false);
}
self.isBusy(false);
});
}

// Previous Page Click
self.previousPage = function () {
if (self.filter().currentPageIndex() > 1) {

var list = [];
self.filter().currentPageIndex(self.filter().currentPageIndex() - 1);
datacontext.getAllPost(self.adarshLogListModel, config.adarshLogUrl, model.adarshLogListModel, self.filter).always(function () {
if (self.filter().currentPageIndex() <= 0) {
self.filter().enablePrev(false);
}
self.adarshLogListModel().userList().forEach(function (item) {
var newRecord = new model.adarshLog();
ko.mapping.fromJS(item, {}, newRecord); //map the json into our oversvable object
list.push(newRecord);
});
self.adarshLogs(list);
// var newFilter = model.filter;
ko.mapping.fromJS(self.adarshLogListModel().filterModel(), {}, self.filter());
//(newFilter);
self.individualPageList(self.adarshLogListModel().filterModel().individualPageList());
if (self.filter().currentPageIndex() <= 1) {
self.filter().enablePrev(false);
}
if (self.filter().currentPageIndex() >= self.filter().totalPageCount()) {
self.filter().enableNext(false);
}
self.isBusy(false);
});
}
else {
self.filter().enablePrev(false);
}
}

//Next page Click
self.nextPage = function () {
if (self.filter().currentPageIndex() <= self.filter().totalPageCount() - 1) {
var list = [];
self.filter().currentPageIndex(self.filter().currentPageIndex() + 1);
datacontext.getAllPost(self.adarshLogListModel, config.adarshLogUrl, model.adarshLogListModel, self.filter).always(function () {
if (self.filter().currentPageIndex() <= 0) {
self.filter().enablePrev(false);
}
self.adarshLogListModel().adarshLogList().forEach(function (item) {
var newRecord = new model.adarshLog();
ko.mapping.fromJS(item, {}, newRecord); //map the json into our oversvable object
list.push(newRecord);
});

self.adarshLogs(list);
// var newFilter = model.filter;
ko.mapping.fromJS(self.adarshLogListModel().filterModel(), {}, self.filter());
self.individualPageList(self.adarshLogListModel().filterModel().individualPageList());
if (self.filter().currentPageIndex() <= 0) {
self.filter().enablePrev(false);
}
if (self.filter().currentPageIndex() >= self.filter().totalPageCount()) {
self.filter().enableNext(false);
}
self.isBusy(false);
});
}
else {
self.filter().enableNext(false);
}
}
//Click on Any Specific Page

self.currentPage = function (index) {
self.filter().currentPageIndex(index);

var list = [];

datacontext.getAllPost(self.adarshLogListModel, config.adarshLogUrl, model.adarshLogListModel, self.filter).always(function () {
self.adarshLogListModel().adarshLogList().forEach(function (item) {
var newRecord = new model.adarshLog();
ko.mapping.fromJS(item, {}, newRecord); //map the json into our oversvable object
list.push(newRecord);
});
self.adarshLogs(list);
// var newFilter = model.filter;
ko.mapping.fromJS(self.adarshLogListModel().filterModel(), {}, self.filter());
//(newFilter);
self.individualPageList(self.adarshLogListModel().filterModel().individualPageList());
if (self.filter().currentPageIndex() <= 1) {
self.filter().enablePrev(false);
}
if (self.filter().currentPageIndex() >= self.filter().totalPageCount()) {
self.filter().enableNext(false);
}
self.isBusy(false);

});

}
};
return viewModel;
}
});

Generic Context. Js

define(['services/logger', 'config'],
function (logger, config) {
getAllPost = function (objectObservable, baseUrl, baseModel, filter) {
var list = [];

var options = {
url: baseUrl + 'GetAll',
data: ko.toJSON(filter),
type: "Post",
contentType: "application/json",
dataType: 'json'

};

return $.ajax(options).then(querySuccess);

function querySuccess(data) {
ko.mapping.fromJS(data, {}, objectObservable);
};
};

var datacontext = {
getAllPost: getAllPost,
};

return datacontext;
});


Filter.cs C# Model

public class Filter
{
public int TotalCount { get; set; }
public int PageSize { get; set; }
public int CurrentPageIndex { get; set; }
public string SortBy { get; set; }
public bool SortAscending { get; set; }
public string SearchText { get; set; }
public string Source { get { return SystemConfig.GetSourceName; } }
public string CountLabel
{
get
{
int progressCountStart = ((CurrentPageIndex - 1) * PageSize) + 1;
int progressCountEnd = (CurrentPageIndex) * PageSize;
if (progressCountEnd > TotalCount)
{
progressCountEnd = TotalCount;
}
return "Showing " + progressCountStart + " to " + progressCountEnd + " of " + TotalCount;
}
}

public int TotalPageCount
{
get
{
int count = 1;
if (TotalCount > 0 && PageSize > 0)
{
double dec = Math.Ceiling((double)TotalCount / PageSize);
count = Convert.ToInt32(dec);
}


return count;
}
}

public List IndividualPageList
{
get
{
List result = new List();
int midPoint = 5;
int totalPagesShowing = 10;
if (TotalPageCount <= totalPagesShowing)
{
for (int i = 1; i <= TotalPageCount; i++)
{
result.Add(i);
}

return result;
}

//Total Page showing 10. Midpoint took as 5. So left is 4 pages and right is 5 pages.
int startpoint = CurrentPageIndex - (midPoint - 1);
int endpoint = CurrentPageIndex + midPoint;

if (startpoint < 1)
{
int surplus = midPoint - CurrentPageIndex;
startpoint = 1;
endpoint = endpoint + surplus;
}

if (endpoint > TotalPageCount)
{
int surplus = endpoint - TotalPageCount;
startpoint = startpoint - surplus;
endpoint = endpoint - surplus;
}

for (int i = startpoint; i <= endpoint; i++)
{
result.Add(i);
}

return result;
}
}

}

Get All WebApi Controller Method

[HttpPost]
public HttpResponseMessage GetAll(Filter filter)
{
HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
try
{
var adarshlogList = adarshLogExtended.GetAll(ref filter);
AdarshLogListModel result = new AdarshLogListModel();
result.AdarshLogList = adarshlogList;
result.FilterModel = filter;
response.Content = new ObjectContent(result, GlobalConfiguration.Configuration.Formatters.JsonFormatter);
}
catch (Exception ex)
{
response.StatusCode = HttpStatusCode.BadRequest;
response.ReasonPhrase = ex.Message;
}

return response;
}


GetAll Repository Method

public List GetAll(ref Filter filter)
{

IQueryable adarshLogList = context.AdarshLog;
if (adarshLogList != null)
{
if (filter != null)
{
filter.TotalCount = adarshLogList.Count();
string searchText = filter.SearchText.ToUpper().Trim();

if (!string.IsNullOrWhiteSpace(searchText))
{

filter.TotalCount = (from p in adarshLogList
where ((p.Name != null && p.Name.ToUpper().Trim().Contains(searchText)) || (p.Id!= null && p.Id.ToString.Contains(searchText)))
select p).Count();

adarshLogList = (from p in adarshLogList
where ((p.Name != null && p.Name.ToUpper().Trim().Contains(searchText)) || (p.Id!= null && p.Id.ToString.Contains(searchText)))
orderby p.AddedDate descending
select p).Skip((filter.CurrentPageIndex - 1) * filter.PageSize).Take(filter.PageSize);
return adarshLogList.ToList();
}
else
{
var pagedList = (from p in adarshLogList
orderby p.AddedDate descending
select p).Skip((filter.CurrentPageIndex - 1) * filter.PageSize).Take(filter.PageSize);

return pagedList.ToList();
}

}
}
return null;
}


Views

Search.cshtml User Control
Footer.cshtml footer User Control

Comments

Popular posts from this blog

How to write secure mvc application using encrypting URL

There are lots ways available to write the secure Mvc application. In my experience I came across lots of secure application in public facing. I want to tell about some of the mechanism I followed. 1- encrypting the URL Parameters and preserving id's encrypted on the client side 1- I always make sure if I pass Id or any sensitive data into the view always make sure it's encrypted. By doing so make sure if we forced to use HTML.hidden or HTML.hidden for have the encrypted values, in action link if I pass any parameters from the client side (eg:- edit or create or navigating between different actions we can make sure that all the values are encrypted) During the design of the actions results if it's http get I usually encrypt the sensitive data [httpget] Public actionresult display() { TestModel testModel=new TestModel(); testModel.id= encrypt(id); Return View(testModel); } [httppost] Public ActionResult Display(string id) { Guid d_id= new Guid(decrypt(id));

Single page application (SPA) using ext.js

what is spa? Single page application are applications that fit in one page with rich and fluid user experiences like a desktop based applications. Why is SPA? All web based elements (html, CSS,javascript) are downloaded from the server on single page load and avoid the continuous page post back. i can explain what this mean. Suppose your web application is made of certain flow and it consists of 5 different pages. Each page need to get data from the user and save before moving to the next page. So when we navigate from one page to other it need to make a round trip to server to store the data in one page and get the data for the next page to display. but in spa we can avoid the continuous post backs. The whole page will not post back any time other than the first load. But it communicate to the server dynamically behind the scene and can achieve the same functionality. Spa using ext.js designing a SPA using ext.js is a challenging task if you are unaware about the ext.js

Sql Server Internals - Named Pipes

Named pipes enables clients applications to request a reliable and two way connection between the client application and Sql Server, across a network. A named pipe has a name which follows the UNC naming convention : \\Server\pipe\name The default names pipe for SQL server is :                 \\Server\pipe\sql\query A named instance would have a named pipe of                \\server\pipe\MSSQL$instancename\sql\query Early versions of SQL Server only provided Named Pipes. Named Pipes also allows for impersonation of a clients credentials. The feature is used by SQL server when using Linked Servers. The clients logon credentials are passed across to the Linked Server for authentication. Named Pipes can operate over TCP/IP, NETBEUI or IPX as it indirectly relies on the Common Internet Files Sytems