Click here to Skip to main content
15,896,269 members
Articles / Web Development / ASP.NET
Tip/Trick

Scroll to Load Data, webservice,javascript

Rate me:
Please Sign up or sign in to vote.
5.00/5 (1 vote)
9 Apr 2013CPOL1 min read 14.2K   383   10  
Load huge data on your web page without postback

Introduction 

The following example will provide information about how we can use web service and JavaScript to load data from server to client page on the basis of browser scrolling.

Background

In this example, I have used web service to get data from server or database using JavaScript.

Using the Code

I am using an ImageUrl class with property named ImgUrl and method getImageUrls:

C#
 public class ImageUrl
{
    /// <summary>
    /// To get url for image
    /// </summary>
    public string ImgUrl {get;set; }

    /// <summary>
    /// Return list of ImageUrl object
    /// </summary>
    /// <returns>ImageUrl[]</returns>s
    public static ImageUrl[] getImageUrls(int offset, int count)
    {
        System.IO.FileInfo[] FileInfos = new System.IO.DirectoryInfo
        (HttpContext.Current.Server.MapPath("~/PRK")).GetFiles("*.jpg");
        ImageUrl[] urls = FileInfos.Select(p => new ImageUrl() 
        {ImgUrl="./PRK/"+p.ToString()}).Skip(offset).Take(count).ToArray();
        return urls;
    }
}  

The second step is to add web service in the project from add new item wizard in project and implement the above method as web method in our service.

C#
// To allow this Web Service to be called from script, 
//using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService] 
public class MyWebService : System.Web.Services.WebService {

    public MyWebService () {

        //Uncomment the following line if using designed components 
        //InitializeComponent(); 
    }

    [WebMethod]
    public string LoadData(int offset,int count) {// offset and count 
    		//to call less data on scrolling event of Browser
        ImageUrl[] imgs =ImageUrl.getImageUrls(offset, count);
        string data = string.Empty;
        foreach (ImageUrl img in imgs)
        {
            data += "<li><img src='"+img.ImgUrl+"' 
            width='100' height='100' /></li>"; // sending html along 
            		//with information i need on page easy to bind :)
        }
        return data;
    }
    
}

Third, we will place service reference for our webservice in scriptmanager on ASP page. It will help us to call webservice method using JavaScript.

Kindly add [System.Web.Script.Services.ScriptService] reference in your web service class to get scripting access for your web service.

ASP.NET
<asp:ScriptManager ID="ScriptManager1" 
runat="server">
<span class="Apple-tab-span" style="white-space: pre;">	
</span><Services>
 <span class="Apple-tab-span" style="white-space: pre;">	
 </span><asp:ServiceReference Path="~/MyWebService.asmx" /> 
 <%-- Provide reference to your web service in script manager --%>
<span class="Apple-tab-span" style="white-space: pre;">	
</span></Services>
</asp:ScriptManager>

In this example, I use a Repeater control to load first time data while page loads.

The ASP.NET page looks like below:

ASP.NET
<div>
        <ul class="ul-class" id="imgLoad">
        <asp:Repeater ID="Repeater1" runat="server">
            <ItemTemplate>
                <li>
                <img src="<%# Eval("ImgUrl") %>" 
                width="100" height="100" />

This is my ASP.NET page code behind class.

Here I am loading first data from server where you can see offset count for method is 0 and count is 42, it will loads first 42 images in repeater.

C#
protected void Page_Load(object sender, EventArgs e)
    {
       // Loading a image from ImageUrl class method name getImageUrls with 0 offset & 40 count
        Repeater1.DataSource = ImageUrl.getImageUrls(0, 42);
        Repeater1.DataBind();
    } 

The next thing is to implement JavaScript to call data from server using web service on browser scrolling. Here whenever browser scrolling happens, I validate the difference between window screen height and document height is less than or equal to the scrolling values of browser.

JavaScript
<script type="text/javascript">
        window.onload = function () {
           
            var offSet = 42;
            var count = 12;
            function loadData(offSet,count) {
                // calling webservice class in javascript
                MyWebService.LoadData(offSet, count, onSuccess, onFailed);
            }
            function onSuccess(Data) {
                // on success 
                document.getElementById("imgLoad").innerHTML += Data;
            }
            function onFailed(ex) {
                alert(ex._message); // alert error message
            }

            window.onscroll = function () {
                var docScroll =document.documentElement;
                if ((docScroll.scrollHeight - window.screen.availHeight) <= docScroll.scrollTop) {
                    offSet += 12;
                    loadData(offSet, count);
                }
            }
        }
        
    </script> 

Points of Interest

For Ajax call, you can use JQuery as well for calling post and get methods from web service.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
-- There are no messages in this forum --