0

I'm searching a clutterless way to paginate data with JQuery and Ajax on a ASP.net website.

I'm trying to make it work similiar to this, but it's not working because there's something wrong on javascript, but I can't find out how to fix it. I actually don't like the results so far, it's too complicate to maintain this code, don't you think?

The question: is there any clutterless way to do the same, using JQuery and Ajax for ASP.NET?

Below I'm sharing some code:

I've got a WebMethod on aspx page code-behind for bringing me sample data:

[WebMethod]
public static string GetEmployees(int pageIndex)
{
    JavaScriptSerializer serial = new JavaScriptSerializer();
    StringBuilder sb = new StringBuilder("[");
    serial.Serialize(new { Id = 1, Name = "Fred G. Aandahl" }, sb); sb.Append(",");
    serial.Serialize(new { Id = 2, Name = "Watkins Moorman Abbitt" }, sb); sb.Append(",");
    serial.Serialize(new { Id = 3, Name = "Amos Abbott" }, sb); sb.Append(",");
    serial.Serialize(new { Id = 4, Name = "Jo Abbott" }, sb); sb.Append(",");
    //more lines here...
    sb.Append("]");
    return sb.ToString();
}

here's the ASPX page:

<!-- Handle pagination -->
<script type="text/javascript" src="default.js"></script>
</head>
<body>
<form id="form1" runat="server">
<div>Members<br/>
    <div id="Pagination" class="pagination"></div>
    <br style="clear:both;" />

    <div id="container">
        <table id="Searchresult" cellspacing="1" cellpadding="0" border="0">
            <tr>
                <th>Id</th><th>Name</th>
            </tr>
            <tr>
                <td>0</td><td>Sample</td>
            </tr>
        </table>
    </div>
</div>
</form>

<form name="paginationoptions">
    <p><label for="items_per_page">Items</label><input type="text" value="5" name="items_per_page" id="items_per_page" class="numeric"/></p>
    <p><label for="num_display_entries">Total links</label><input type="text" value="10" name="num_display_entries" id="num_display_entries" class="numeric"/></p>
    <p><label for="num">Start /End point</label><input type="text" value="2" name="num_edge_entries" id="num_edge_entries" class="numeric"/></p>
    <p><label for="prev_text">Previous label</label><input type="text" value="Prev" name="prev_text" id="prev_text"/></p>
    <p><label for="next_text">Next label</label><input type="text" value="Next" name="next_text" id="next_text"/></p>
    <input type="button" id="setoptions" value="Aceptar" />
</form>


The default.js

// This file demonstrates the different options of the pagination plugin
// It also demonstrates how to use a JavaScript data structure to 
// generate the paginated content and how to display more than one 
// item per page with items_per_page.
var emps;
/**
* Callback function that displays the content.
*
* Gets called every time the user clicks on a pagination link.
*
* @param {int}page_index New Page index
* @param {jQuery} jq the container with the pagination links as a jQuery object
*/
function pageselectCallback(page_index, jq) {

    //read data for pagination from webmethod GetEmployees

    var data = '{"pageIndex":' + page_index + '}';
    $.ajax({ type: 'Post',
        url: 'Default.aspx/GetEmployees',
        data: data,
        contentType: "application/json;charset=utf-8",
        dataType: 'json',
        success: function(msg) {
            emps = eval(msg.d);

            $.each($('#Searchresult tr:gt(0)'), function(i, n) {
                $('#Searchresult')[0].deleteRow(n.rowIndex);
            });

            // Get number of elements per pagionation page from form
            var items_per_page = $('#items_per_page').val();
            var max_elem = Math.min((page_index + 1) * items_per_page, emps.length);
            var newcontent = '';
            for (var i = page_index * items_per_page; i < max_elem; i++) {

                var emp = emps[i];
                newcontent += '<tr><td>' + emp.Id + '</td><td>' + emp.Name +     '</td></tr>';
            }

            // Replace old content with new content
            $('#Searchresult').html(newcontent);

            //can't make it work
            //var optInit = { callback: pageselectCallback }; // getOptionsFromForm();
            //$("#Pagination").pagination(emps != null ? emps.length : 0, optInit);

        },
        error: function(msg) {
            alert("error:" + msg.statusText);
        }
    });


    // Prevent click eventpropagation
    return true;}



// The form contains fields for many pagiantion optiosn so you can 
// quickly see the resuluts of the different options.
// This function creates an option object for the pagination function.
// This will be be unnecessary in your application where you just set
// the options once.
function getOptionsFromForm() {
    var opt = { callback: pageselectCallback };
    // Collect options from the text fields - the fields are named like their option     counterparts
    $("input:text").each(function() {
        opt[this.name] = this.className.match(/numeric/) ? parseInt(this.value) :     this.value;
    });
    // Avoid html injections in this demo
    var htmlspecialchars = { "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" }
    $.each(htmlspecialchars, function(k, v) {
        opt.prev_text = opt.prev_text.replace(k, v);
        opt.next_text = opt.next_text.replace(k, v);
    })
    return opt;
}

// When document has loaded, initialize pagination and form 
$(document).ready(function() {
    // Create pagination element with options from form
    var optInit = getOptionsFromForm();
    $("#Pagination").pagination(emps!=null?emps.length:0, optInit);

    // Event Handler for for button
    $("#setoptions").click(function() {
        var opt = getOptionsFromForm();
        // Re-create pagination content with new parameters
        $("#Pagination").pagination(emps != null ? emps.length : 0, opt);
    });


});

1 Answer 1

0

I'd like to share my approach. Bear in mind that I have no knowledge of ASP.NET, but I think these steps will work regardless the language is.

First I create a page that work without JavaScript enabled. The pagination will be a link to current page with page number passed in either URI segment or in a get parameter. This way, the page is still usable without JavaScript enabled in the browser.

Next step is to add a progressive enhancement to those who have JavaScript enabled in the browser. I add a simple if in both controller and the view to determine if the request is a normal request or AJAX request. If it a normal request, serve the page completely. If it an AJAX request, only give part of the page, in this case the table or list part.

The jQuery code to change pagination into AJAX will be like this:

jQuery(function($){
  $(".pagination").click(function(){
    //determine the URL
    var url = $(this).attr("href");
    $.get(url,
      { nbRandom: Math.random() },
      function(data){
        $("#container").html(data);
      });
  });
});

The code above will replace the content of <div id="container"> with the AJAX response (it will be contain only table part).

Remember to use GET if it will only fetch the data, and use POST if the request will change something (add/edit, delete, login, etc). nbRandom in the parameter is just a hack to prevent caching in IE. It use a parameter name that not used in the server side page.

This is my way to implement AJAX pagination in my application. I hope you can get the concept and implement your own.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.