CODEDIGEST
Home » Articles
Search
 

Technologies
 

Sponsored links
 

CodeDigest Navigation
 

Technology News
No News Feeds available at this time.
 

Community News
No News Feeds available at this time.
 
Lazy Loading jQuery Collapsible Panel in ASP.Net Using JSON

By Satheesh Babu
Posted On Aug 26,2009
Article Rating:
Be first to rate
this article.
No of Comments: 1
Category: jquery
Print this article.

Lazy Loading jQuery Collapsible Panel in ASP.Net Using JSON

 

One of my previous article  Building Collapsible Panel Control using jQuery in ASP.Net Page discussed the basics of collapsible panel and building a simple collapsible panel with jQuery library in an asp.net page. The collapsible panel in my previous article is fully loaded with the contents when the page is initially rendered to the client. Hence, clicking the arrow buttons on the panel will just expand and collapse the contents. This will make the page heavy when there are large amount of data on different panels on the page. It will be better and light weight when we actually load the contents of the panels only when the user clicks the expand arrow button, a lazy loading or loading on-demand.

Moving forward, we will create a jQuery collapsible panel that can load the data only when it is required. We will use the same collapsible panel implementation we used in my previous article. We will populate the panels with articles list in different categories.

 

Steps

1.      Open Visual Studio 2008 from the Start menu. Click File > New > Website and select ASP.Net Website from "Visual Studio Installed templates".

2.      Choose a language of your choice(I have selected C#) and name the website as per the need.

3.      Download the latest jQuery library from jQuery.com and integrate into your project. Read the following Faq’s to integrate jQuery library to your project.

What is jQuery? How to use it in ASP.Net Pages?

How to enable jQuery intellisense in Visual Studio 2008?

How to use jQuery intellisense in an external javascript file?

4.      Next, we will define our collapsible panels in our asp.net page. For simplicity purpose, i will define 3 panels to load articles in 3 different categories.

<div id="ContainerPanel" class="ContainerPanel">

        <div id="header" class="collapsePanelHeader">

            <div id="dvHeaderText" class="HeaderContent">ASP.Net Articles</div>

            <div id="dvArrow" class="ArrowExpand" title="ASP.Net"></div>

        </div>

        <div id="dvASPNET" class="Content" style="display:none">          

        </div>

    </div>

  

   <br />    

    <div id="Div1" class="ContainerPanel">

        <div id="Div2" class="collapsePanelHeader">

            <div id="Div3" class="HeaderContent">Csharp Articles</div>

            <div id="Div4" class="ArrowExpand" title="Csharp"></div>

        </div>

        <div id="dvCSharp" class="Content" style="display:none">          

        </div>

    </div>

 

    <br />

     <div id="Div6" class="ContainerPanel">

        <div id="Div7" class="collapsePanelHeader">

            <div id="Div8" class="HeaderContent">jQuery Articles</div>

            <div id="Div9" class="ArrowExpand" title="jQuery"></div>

        </div>

        <div id="dvjQuery" class="Content" style="display:none">          

        </div>

    </div>

Script

$(document).ready(function() {

                $("DIV.ContainerPanel > DIV.collapsePanelHeader > DIV.ArrowExpand").toggle(

                function() {

                    $(this).parent().next("div.Content").show("slow");

                    $(this).attr("class", "ArrowClose");

                },

                function() {

                    $(this).parent().next("div.Content").hide("slow");

                    $(this).attr("class", "ArrowExpand");

                });

 

            });

To identify the article category to populate for a particular panel, we will add a title property [bolded text in the above code] to the div tag that holds in expand/collapse button. When the user clicks the expand button, we will call an ashx handler which can accept an article category [obtained from the title property of the div] and return a json string of article list on that category.

5.      Now, we will add an ashx hander that can get article category as a query string and return list of articles on that category in json format. To do this, Right click the project in solution and click “Add New Item”. Select “Generic Handler”. I have named as GetArticles.ashx. Refer the below code,

 

public class GetArticles : IHttpHandler {

   

    public void ProcessRequest (HttpContext context) {

 

        string Category = context.Request.QueryString["Cat"];

        //Pass the article category as paramter to the query

        string query = "SELECT * FROM [Articles]";

        DataTable dt = GetDt(query);

        StringBuilder strArticles = new StringBuilder();

 

        if (dt != null)

        {

            strArticles.Append("{ Articles:[");

            for (int i = 0; i < dt.Rows.Count; i++)

            {

                strArticles.Append("{");

                strArticles.Append("\"ArticleID\":\"" + dt.Rows[i]["ArticleID"].ToString() + "\",");

                strArticles.Append("\"Title\":\"" + dt.Rows[i]["Title"].ToString() + "\",");

                strArticles.Append("\"Category\":\"" + dt.Rows[i]["Category"].ToString() + "\",");

                strArticles.Append("\"Author\":\"" + dt.Rows[i]["Author"].ToString() + "\",");

                strArticles.Append("\"URL\":\"" + dt.Rows[i]["URL"].ToString() + "\"");

                if (i != dt.Rows.Count - 1)

                {

                    strArticles.Append("},");

                }

            }

        }

        strArticles.Append("}");

        strArticles.Append("]}");

        context.Response.ContentType = "application/json";

        context.Response.ContentEncoding = Encoding.UTF8;

        context.Response.Write(strArticles.ToString());

        context.Response.End();

    }

 

    public bool IsReusable {

        get {

            return false;

        }

    }

    public DataTable GetDt(string query)

    {

        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Sql"].ConnectionString);

        SqlDataAdapter ada = new SqlDataAdapter(query, con);

        DataTable dt = new DataTable();

        ada.Fill(dt);

        return dt;

    }

 

}

In the above code, i am returning the articles on all categories without doing filtration. You can rewrite the query to filter based on the querystring value. The above handler will fetch the data from the SQL express database in App_Data folder. I have created the JSON format manually. If you have ASP.Net AJAX installed on the server you can try using JavaScriptSerializer class packed in System.Web.Script.Serialization namespace to convert objects to JSON format. You can also try using DataContractJsonSerializer class for creating json strings.

6.      Next, we will call the ashx handler when the user clicks expand button and pass the title as a querystring to the handler to get json list of articles. We will populate the panel with the list of article in tabular format using returned json string.  To make it simple, we will use jTemplate plugin to format the json into a tabular format and populate it in the panel.

You can visit the jTemplate site here to know more aboute jTemplate plugin.

Integrating jTemplate plug-in in your Project

1.      Grab the newer version of jTemplate plug-in either from jTemplate site or jQuery site.

2.      Copy the plug-in to your solution and link it through script tag.

<script src="_scripts/jquery-jtemplates.js" type="text/javascript"></script>

 

First, we will build our tabular template that is required to populate the json string. Include an htm file into the solution and name it as temp.htm. Refer the below code for the template,




<table>

  <thead>

    <tr style="background-color:Maroon;color:White;">

      <th>Article ID</th>

      <th>Title</th>

      <th>Category</th>

      <th>Author</th>    

    </tr>

  </thead>

  <tbody>

   {#foreach $T.Articles as record}

    <tr>

      <td>{$T.record.ArticleID}</td>

      <td><a href="{$T.record.URL}">{$T.record.Title}</a></td>

      <td>{$T.record.Category}</td>

      <td>{$T.record.Author}</td>                     

    </tr>

    {#/for}

  </tbody>

</table>

 

Calling the Handler and using jTemplate to populate the Panel

Now, we will modify the code given in step 4 to call the ashx handler when the user click expand button to load the data on that panel. We will read the article category from the “title” property and call the handler using getJSON() method in jQuery. The code can be rewritten as,

 

<script src="_scripts/jquery-1.3.2.min.js" type="text/javascript"></script>

       <script src="_scripts/jquery-jtemplates.js" type="text/javascript"></script>  

        <script language="javascript">

            $(document).ready(function() {

                $("DIV.ContainerPanel > DIV.collapsePanelHeader > DIV.ArrowExpand").toggle(

                function() {

                    var title = $(this).attr("title");

                    if (title == "ASP.Net") {  

                        BindArticles(title, 'dvASPNET');

                    }

                    else if (title == "Csharp") {

                    BindArticles(title, 'dvCSharp');

                    }

                    else if (title == "jQuery") {

                    BindArticles(title, 'dvjQuery');

                    }

 

                    $(this).parent().next("div.Content").show("slow");

                    $(this).attr("class", "ArrowClose");

                },

                function() {

                    $(this).parent().next("div.Content").hide("slow");

                    $(this).attr("class", "ArrowExpand");

                });

 

            });

 

            function BindArticles(Category, Container) {

                $.getJSON('GetArticles.ashx?Cat=' + Category, function(articles) {                                              

                    $('#' + Container).setTemplateURL('temp.htm');

                    $('#' + Container).processTemplate(articles);                  

                });

            }          

        </script>

The BindArticles() method in the above code will call the handler and use jTemplate plugin to generate tabular view of the article list inside the clicked panel. You can also generate the tabular view manually by reading the json string and constructing an html table.

 

Execute the page and see it in action. You can see an output similar to below,

Lazy Loading/On Demand jQuery Collapsible Panel in ASP.Net Using JSON

 

Download the code attached with this article.

Downloads

Download Source 

Conclusion

The lazy loading or on-demand load is a really an efficient mechanism if we have large amount of data to be loaded on the page. At a point of time, the user may not be interested in all the data the page has and this feature helps us to load the data only the user requires. The jQuery implementation to fetch the data is obviously a light weight when compared to other ajax techniques.

Happy Coding!!!

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments
Ajax vs SEO
Loading content using Ajax like this definitely improves the user experience but at the same time Search Engines would get less content to crawl.

How to balance it right?

Regards,
Nikunj Dhawan