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.
 
Creating Accordion Panel using jQuery in ASP.Net – Part 2[Loading the Accordion Panel in ASP.Net]

By Satheesh Babu
Posted On Jan 14,2009
Article Rating:
Be first to rate
this article.
No of Comments: 0
Category: jQuery
Print this article.

Creating Accordion Panel using jQuery in ASP.Net – Part 2

Lazy Loading the Accordion Panel in ASP.Net

 

My previous article, Creating Accordion Panel using jQuery in ASP.Net – Part 1 discussed about creating an Accordion panel ourselves using jQuery library in an ASP.Net page.

Re-cap

 Accordion control is a HTML display control packed with multiple collapsible panels. This control allows users to expand only one panel at a time.

Read Creating Accordion Panel using jQuery in ASP.Net – Part 1 to know more about building accordion panel using jquery.

 

The Accordion panel we created in the previous article will load the contents in the content div at the very first load of the page. This means, we still populate the data in every content div but it is just hidden to the users. If your requirement is to load large number of panels with large data then loading all the panels at a stretch will not be a good idea. Also, there are high chances that every user will not be interested in the data in every panel of your Accordion control. Doing like this will simply make your page bulky and will affect the page load time. To answer this difficulty, we will lazy load the accordion panel in this article. Lazy loading is a technique where we will load the data only if it is required i.e. on-demand loading. To be clear, when a user clicks a particular panel only then the data will be loaded for the panel.

 

If you are new to jQuery, i recommend you to read the below FAQ’s to have a quick understanding.

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?

 

Read the below article, to know more about jQuery library and its advantages,

Introduction to jQuery in ASP.Net and 10 Advantages to Choose jQuery

 

I will include all the steps to create an Accordion Panel from the previous article to help the readers to understand it better.

Steps

1.      From Start menu, Open Visual Studio 2008.

2.      Create a new Asp.Net website from File menu. To do that, Click New> Website and choose “ASP.Net Web Site” and select the language of your choice. I have used C# in this article.

3.      Similar to Part 1, we will create a accordion control using DIV tags.  Refer the below code,

 

    <div class="Accordion">  

        <div id="header" class="collapsePanelHeader" title="ASP.Net">

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

        </div>

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

        <br />

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

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

        </div>

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

        <br />    

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

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

        </div>

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

    </div>

 

Below, you can find the definition of 3 css stylesheet class used in the above HTML.

<style>

/*CollapsiblePanel*/

.collapsePanelHeader

{

       width:402px;

       height:30px;

       background-image: url(images/bg-menu-main.png);

       background-repeat:repeat-x;

       color:#FFF;

       font-weight:bold;

       cursor:hand;

       cursor:pointer;

}

.HeaderContent

{

       float:left;  

       padding-left:5px;

}

.Content

{

       width:400px;

       border:1px;

       border-color:#1052a0;     

       border-style:double;

}

</style>

 

4.      Get the new jquery library from here and integrate it into your project. Refer the FAQ’s above.

5.      Now, as a first step, we will provide the accordion control effect using jQuery script and then we will see how to do lazy loading of content in Accordion panels. Refer the below code,

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

<script type="text/javascript">

    $(document).ready(function() {       

        $("DIV.Accordion > DIV.collapsePanelHeader").click(function() {

            $(this).next("DIV.Content").slideToggle("slow");

            $("DIV.Accordion > DIV.Content").not($(this).next("DIV.Content")).slideUp("slow");

        });

    });

</script>

 

In the above script, the jQuery.slideToggle() method will expand the content div if it is in collapsed state or it will do the viceversa.

6.      That’s it. Execute the page and you can see the Accordion panel in action.

7.      Next, we will lazy load the data for each panel when the user clicks its header.  We will first develop an httphandler which can be called from the jquery to load the contents for the clicked panel. Refer the below code. The below httphandler will accept category id as query string to fetch the data for the particular category. The fetched data will be then converted to JSON string and will be returned to the caller through the Response object.

 

public class GetArticles : IHttpHandler {

   

    public void ProcessRequest (HttpContext context) {

 

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

        //pass the category id and fetch the required data

        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 have fetched all the data from the Article table without filtering. You can filter the data as per your requirement.

8.      Now, we will re-write the jquery code for Accordion functionality (step 5) to call the HttpHandler and pass the title (Category ID) of the header as a querystring to the httphandler to get json list of articles.

We will then 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.

What is jTemplate?

jTemplate is a JavaScript template engine which can be used to display json data in tabular formats quickly. Visit the jTemplate site here.

Steps to integrate the jTemplate in your Project

1.      Download the latest 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 html 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 Hanlder and using jTemplate to populate the Panel

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

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

        <script type="text/javascript">

            $(document).ready(function() {            

                $("DIV.Accordion > DIV.collapsePanelHeader").click(function() {

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

 

                    if ($(this).next("DIV.Content").html() == "") {

                        BindArticles(title, $(this).next("DIV.Content"));

                    }

                    else {

                        $(this).next("DIV.Content").slideToggle(800);

                        $("DIV.Accordion > DIV.Content").not($(this).next("DIV.Content")).slideUp("slow");

                    }

 

                });

            });

 

            function BindArticles(Category, Container) {

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

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

                    $(Container).processTemplate(articles);

                    $(Container).slideToggle();

                    $("DIV.Accordion > DIV.Content").not(Container).slideUp("slow");

                });

            }

          

        </script>

The BindArticles() method in the above code will call the httphandler and use jTemplate plugin to generate tabular view of the articles for the corresponding panel. You can also generate the tabular view manually by reading the json string and constructing an html table.

9.      That’s it! Execute the page and see lazy loading of Accordion panel in action.

 

Downloads

Download Source

 

Conclusion

The introduction of jquery has made the many complex client side task easier. Accordion panel is another example which proves the simplicity of jquery and the lazy loading feature discussed in this article proves how simple is making an AJAX call using jQuery. Download the source attached with this article and see it in action.

Happy Coding!!

 

 

Similar Articles
You can contribute to CodeDiget.Com:
Donate to CodeDigest.com
Article Feedback
Comments