English 中文(简体)
我在哪里可以找到带有ASP.NET Ajax的jQuery分页示例?
原标题:Where can I find a sample for jQuery Pagination with AJAX for ASP.NET?

我正在寻找一种简洁的方法,用于在ASP.net网站上使用JQuery和Ajax分页数据。

我正在尝试将它与这个类似,但它不起作用,因为javascript出了问题,但我找不出如何修复它。实际上,我不太喜欢目前的结果,这段代码维护起来太麻烦了,您认为呢?

问题:是否有一种无杂乱的方式来使用JQuery和Ajax进行ASP.NET的操作?

以下是我分享的一些代码:

我在aspx页面后台代码中有一个WebMethod,用于提供示例数据。

[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>


违约。 j)

// 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);
    });


});
最佳回答

我想分享我的方法。记住,我不懂ASP.NET,但我认为这些步骤不管使用什么编程语言都是有效的。

首先,我创建了一个可以在没有启用JavaScript的情况下工作的页面。分页将是当前页面的链接,并将页面编号传递到URI段中或以get参数进行传递。这样,即使在浏览器中没有启用JavaScript,页面仍然可以使用。

下一步是为那些浏览器启用了JavaScript的人添加渐进增强功能。我在控制器和视图中都添加了一个简单的if语句,以确定请求是正常请求还是AJAX请求。如果它是正常请求,请完全提供页面。如果是AJAX请求,则只提供页面的一部分,即表格或列表部分。

把分页改变成AJAX的jQuery代码将会是这样的:

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

上面的代码将用 AJAX 响应替换 <div id="container"> 的内容(它只包含 table 部分)。

记住,如果仅需要获取数据,请使用GET,如果请求将更改某些内容(添加/编辑、删除、登录等),请使用POST。参数中的nbRandom只是一种在IE中防止缓存的技巧。它使用一个在服务器端页面中未使用的参数名称。

这是我在应用程序中实现AJAX分页的方法。我希望您能理解这个概念并实现自己的方法。

问题回答

暂无回答




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Transaction handling with TransactionScope

I am implementing Transaction using TransactionScope with the help this MSDN article http://msdn.microsoft.com/en-us/library/system.transactions.transactionscope.aspx I just want to confirm that is ...

System.Web.Mvc.Controller Initialize

i have the following base controller... public class BaseController : Controller { protected override void Initialize(System.Web.Routing.RequestContext requestContext) { if (...

Microsoft.Contracts namespace

For what it is necessary Microsoft.Contracts namespace in asp.net? I mean, in what cases I could write using Microsoft.Contracts;?

Separator line in ASP.NET

I d like to add a simple separator line in an aspx web form. Does anyone know how? It sounds easy enough, but still I can t manage to find how to do it.. 10x!

热门标签