|
Lazy Loading jQuery Collapsible Panel in ASP.Net Using JSON |
|
Moving forward, we will create a jQuery collapsible panel that can load the data only when it is required. We will populate the panels with articles list in different categories. |
|
Steps
|
- Open Visual Studio2008, Click File >Website and choose ASP.Net Website.
- Select a language of your choice. I have selected C#. You can name your website as per your need.
- 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.
- Next, we will define our collapsible panels in our asp.net page. For simplicity purpose, we 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.
|
- 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”. We 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, we are 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. |
|
- 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.
|
What is jTemplate?
|
jTemplate is a simple JavaScript template engine which can be used to present json data in tabular format. jTemplate provides language oriented features like conditional statements, loops, etc for building up templates. You can visit the jTemplate site here.
|
Steps to integrate the jTemplate in your Project |
- Download the latest version of jTemplate plug-in either from jTemplate site or jQuery site.
- 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);
});
}
|
The BindArticles() method in the above code will call the handplugin 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,
|
 |
|
|