Load Content While Scrolling With jQuery and MVC 3.0

 Source:http://www.webresourcesdepot.com/load-content-while-scrolling-with-jquery/   <---

http://webdeveloperplus.com/jquery/create-a-dynamic-scrolling-content-box-using-ajax/
http://superdit.com/2011/04/07/jquery-collapsible-load-scroll/
 
Content structure  look like:
<div class="contentlatest" data-id="8"> Some content is here... </div>
<div class="contentlatest" data-id="9">Some content is here...</div>


Firstly,I created a controller like:
       public ActionResult Content()
        {
            int count = 5;
            var list = JokeRepository.FindAll().OrderByDescending(j => j.CreateTime).Take(count);
            return View(list);
        }
        public ActionResult ScrollToContent(int  lastId )
        {
            int count = 5;
            var list = JokeRepository.FindAll()
                .Where(i => i.Id <  lastId )
                .Take(count).OrderByDescending(i => i.Id);
           
            return Json(list,JsonRequestBehavior.AllowGet);
        }
 
Then,a view is created.
@model IEnumerable<Funny.Models.Joke>
 
@foreach (var item in Model)
{
    <div class="contentlatest"  data-id ="@item.Id">@item.Title</div>
}
<div id="lastpost-loading">
</div>
 
Finally,let's write some js to achieve scroll to load data.
<script type="text/javascript">
    $(document).ready(function () {
    var fetching = false;
        var lastPost = function () {
        fetching = true;
            $('div#lastpost-loading').html('<img src=\'#\'" /Content/images/loading.gif">');
            $.post("/Admin/Admin/Scroll?lastId=" + $('.contentlatest:last').data('id'),
            function (data) {
                if (data) {
                    for (var i in data) {
                        $('.contentlatest:last').after($.format('<div class=\"contentlatest\" data-id=\"{0}\">{1}</div>', data[i].Id, data[i].Title));
                    }
                }
                setTimeout(function(){
                fetching = false;
                },300);
                $('div#lastpost-loading').empty();
            }, "json");
        };

        $(window).scroll(function () {
            var bufferzone = $(window).scrollTop() * 0.20;
            if (!fetching && ($(window).scrollTop() + bufferzone > ($(document).height() - $(window).height()))) {
                lastPost();
            }
            else{
            $('div#lastpost-loading').text('data loaded');
            }
        });
    });
</script>
 
Hope this help,
Lisknove.

你可能感兴趣的:(jquery,Web,mvc,.net,C#,it)