質問

I'm looking to implement some simple endless pagination for a comments section, similar to Youtube comments where you click Show More at the bottom and it loads a few more comments but maintains state for the previous ones.

I think I can do it in an UpdatePanel with a ListView with the Ajax control toolkit and a bit of Jquery, but just need some guidance. I was thinking of displaying the first 4 items that come back and databind them to my ListView, the ListView would be wrapped in a UpdatePanel with a "Show More" button, when the button is clicked it would add 4 more to the datasource and rebind the ListView, but this would not smoothly add the 4 comments tot he bottom, rather the ListView section would refresh to show the new comments.

Is there a smoother/better way of doing this? I am using Webforms.

役に立ちましたか?

解決

Honestly, I would avoid the whole web forms model for this (including the UpdatePanel). It adds a lot of overhead and complexity in this case.

Send an AJAX request back to a handler (whatever it may be, ASPX page built for this purpose, web method, HttpHandler, MVC controller, etc.) and return JSON. Since comments are fairly simple structurally, it shouldn't be hard to insert/build the associated markup as needed.

I have built an endless comment system in an ASP.Net web forms app using this approach, and it works great. The page is rendered as a normal ASPX with user controls. The user control for comments only outputs a bit of script.

I load my initial comments using a request to a controller, and as the user scrolls I simply ask the controller for the next block of data until the controller tells me that I have reached the end of the set (you could also add a cap so that the user doesn't load too many records and crash their browser).

Example

  • Make request using jQuery.ajax()
  • In your success callback, you may treat the data passed to it as a JavaScript object
  • Loop through all items and create/append DOM nodes.

var element = $("#comments"); // this is your node with all comments

$.ajax({
    type: "POST",
    url: "ClientApi/Comments/_GetPaged", // this handler builds JSON
    dataType: "json",
    data: { pageIndex: 5 }, // your input values here
    cache: false,
    success: function (data) {
        for (var i = 0; i < data.length; i++) {
            var comment = data[i];
            var itemElement = $("<div/>").appendTo(element);

            // do whatever you want here, just remember that user input 
            // should be sanitized somewhere during the process
            itemElement.html(comment.text);
        }
    }
});
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top