Search code examples
jsonmodel-view-controllerjsonresult

how to pagination JSONResult in MVC with ajax url data loading?


I have a problem in pagination with a json result data in MVC. Below code is my ajax data loading:

jQuery.ajax({
        url: "/Products/Search",
        type: "POST",
        dataType: "json",
        success: function (data) {
            displayData(data);
        },
        error: function (errdata, errdata1, errdata2) { $('#ProductList').html("Error in connect to server" + errdata.responseText); }

and my controller JsonResult is below:

public JsonResult List()
        {
            tbl = db.tblProducts;
            return Json(tbl, JsonRequestBehavior.AllowGet);
        }

I can recive data from above ajax data loading successfully, but I can't pagination it. Please help me. Thank you.


Solution

  • There is no code for Pagination,Do you want to do client side pagination or server side

    Thinking your devloping an ASP.Net MVC application

    Server side pagnation : You can load the specific number of records alone. Using Skip and Take functionlitys

    public JsonResult GetOrders(int pagesize, int pagenum)
            {
                var query = Request.QueryString;
                var dbResult = db.Database.SqlQuery<Order>(this.BuildQuery(query));
                var orders = from order in dbResult
                            select new Order
                            {
                                ShippedDate = order.ShippedDate,
                                ShipName = order.ShipName,
                                ShipAddress = order.ShipAddress,
                                ShipCity = order.ShipCity,
                                ShipCountry = order.ShipCountry
                            };
                var total = dbResult.Count();
                orders = orders.Skip(pagesize * pagenum).Take(pagesize);
                var result = new
                {
                    TotalRows = total,
                    Rows = orders
                };
                return Json(result, JsonRequestBehavior.AllowGet);
            }
    

    Client side pagination : Load the entire records to your view from there implement pagination

    Sample code : http://jsfiddle.net/rniemeyer/5xr2x/