jQuery Infinite Scroll with MVC 2

The inspiration for this post came from answering a question on Stack Overflow:
jQuery Infinite Scroll and Gridview

Controller:
[sourcecode language="csharp"]

/// <summary>
/// GET: /Widget/Search/
/// Displays search results.
/// </summary>
/// <param name="s"></param>
/// <returns></returns>
public ActionResult Search(SearchType searchType, string s, [DefaultValue(1)]int page)
{
try
{
int batch = 20;
int fromRecord = 1;
int toRecord = batch;

if(page != 1)
{
toRecord = (batch * page);
fromRecord = (toRecord – (batch-1));

}

var widgets= _repos.Search(searchType, s, fromRecord, toRecord );

if (widgets.Count == 0)
{
InfoMsg("No widgets were found.");
}

if (Request.IsAjaxRequest())
{
if(widgets.Count > 0)
{
return View("SearchResultsLineItems", widgets);
}
else
{
return new ContentResult
{
ContentType = "text/html",
Content = "noresults",
ContentEncoding = System.Text.Encoding.UTF8
};
}

}

return View("SearchResults", widgets);
}
catch (Exception ex)
{
return HandleError(ex);
}
}

[/sourcecode]

View:
[sourcecode language="csharp"]
<% if (Model.Count > 0) { %>
<table id="tblSearchResults">
<tr>
<th></th>
<th>Col1</th>
<th>Col2</th>
<th>Col3</th>
<th>Col4</th>
<th>Col5</th>
<th>Col6</th>
</tr>
<% Html.RenderPartial("SearchResultsLineItems", Model); %>
</table>
<div id="loadingSearchResults" style="text-align:center;height:24px;"></div>
<div id="actionModal" class="modal"></div>
<% } %>
[/sourcecode]

Script:
[sourcecode language="csharp"]

$(document).ready(function() {
initAutoPaging();
});

function initAutoPaging() {
$(window).scroll(function () {
if ($(window).scrollTop() == $(document).height() – $(window).height()) {
loadMore()
}
});
}

var current = 1;
function loadMore() {
if (current > -1) {
if (!_isShowingDetails)
{
if (!$(‘#loadingSearchResults’).html()) {
current++;
$(‘#loadingSearchResults’).show();
$(‘#loadingSearchResults’).html("<img src=’/content/images/loading.gif’ />");
$.ajax({
async: true,
url: document.URL + "?&page=" + current,
contentType: "application/x-www-form-urlencoded",
dataType: "text",
success: function(data) {
if (data != ‘noresults’) {
$(‘#tblSearchResults tr:last’).after(data);
$(‘#loadingSearchResults’).hide();
$(‘#loadingSearchResults’).html(”);
highlightSearch();
} else {
current = -1;
$(‘#loadingSearchResults’).show();
$(‘#loadingSearchResults’).html("<h3><i>– No more results — </i></h3>");
}
}
});
}
}

}
}

[/sourcecode]

One Response to jQuery Infinite Scroll with MVC 2

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>