Click here to Skip to main content
Click here to Skip to main content

Row Expand Collapse using JQuery and Ajax

By , 18 Aug 2010
 

Introduction

Nowadays, an important issue with web applications is how quickly a web page is rendered and how it is animated or visualized.

So for a quick reply from the server, Ajax is the solution and for some visualizations with server side response, we mostly use jquery or JavaScript.

In this article, for expanding, collapsing and adding details to gridview row, we are going to use AJAX to make a call to the server and we will visualize it using jquery.

Aim

  1. Getting details of product by extracting details at the next to current row and before second one.
  2. Visualizing the expanding of rows.
  3. No server side postback.
  4. Using GridView control to bind data and simple data binding to table using scriptlet.

Using Jquery Code

Expanding Row

For expanding any row, we need to create a new row with the serverside details and then we will add it to the next of current row:

rowexpand.png

var trindex=0;	//trindex hold row index created by jquery
$("tr").click(function() {
if ($(this).find("td:first").length > 0) { //check whether it is header or content row
//row index increment to assign new row id everytime
trindex++;
//create a row with td colspan 3 to show product description
var row= '><td class="currRow" colspan="3" ><
div id="did"><img id="imagepath" src=""
style="height: 81px; width: 104px" />  Description :<
span id="des">sd</span><p>Cost :<
span id="cost">sd</span></p></div></td></tr>';

//adding animation to row
var newRow = $("<tr id=tr"+ trindex + row).animate({
height: "140px",
opacity: 0.25,
}, 500);
//adding row to existing table
$(this).after(newRow);
Collapsing Row

At the same moment we expand any row, we collapse the previous created row, so we need to remember the previous created rowIndex or its id.

gridcollapsed.png

$("#"+rowName).find('td').removeClass('currRow').addClass('hideRow');
$("#"+rowName).animate({
    height: "0px",
    opacity: 0.25,
    }, 1000, function() {
$("#"+rowName).remove();
Ajax Call to the Server

For getting the full details about our shortly highlighted product, we need to make an asynchronous call to server using AJAX. We are passing some key values to server(product Id) to extract the resultset.

$.ajax({
       type: "POST",
       url: "WebService.asmx/GetDetails",   //webserviceName/methodName
       data: "{'name': '" + $(this).find("td span").text()
       + "'}",  //passing values to webservice(productid)
       contentType: "application/json; charset=utf-8",
       dataType: "json",
       success: function(msg) {
       //extracting response data to newly created row
       $("#tr"+trindex ).find("td #did p #cost").text(msg.d.id );
       $("#tr"+trindex ).find("td #did  #des").text(msg.d.order);
       $("#tr"+trindex ).find("td #did #imagepath").attr
       ('src', msg.d.order); //$("#myImage").attr("src", "path/to/newImage.jpg");
       },
       error: FailedMessage     //showing error message if failure
       }); 
Using the WebService.cs

Programmable application logic is accessible via standard Web protocols. We are using webservice to extract data from database using jquery Ajax call, CollectData class to hold extracted details from db.

public class CollectData
{
        public string cost { get; set; }
        public string imagePath { get; set; }
        public string description { get; set; }
}

Simple queries to the database via WebMethod:

[WebMethod()]
    public CollectData GetDetails(string name)
    {
        SqlConnection con = new SqlConnection
	(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
        SqlCommand cmd = new SqlCommand("Select cost, imagePath, 
		description from Products where ProductId='" + name + "'",con);
        SqlDataReader data;
        CollectData c = new CollectData();
        try
        {
            con.Open();
            data=cmd.ExecuteReader();
            if (data.Read())
            {
                c.cost= data[0].ToString();
                c.imagePath = data[1].ToString();
                c.description = data[2].ToString();
                return c;
            }
            else
            {
                c.cost = "N/A";
                c.imagePath = "N/A";
                c.description = "N/A";
                return c;
            }
        }
        catch (Exception ex)
        {
            c.cost = "N/A";
            c.imagePath = "N/A";
            c.description = "N/A";
            return c;
        }
    }

Conclusion

We have mixed up Jquery, Ajax, server control (Gridview) to get quick and visualized output. Result can be slightly different depending on the browsers.

History

  • 18th August, 2010: Initial post

License

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

About the Author

jayantbramhankar
Student
India India
Member
I'm student (CE).

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 2memberafzal.gujrat17 Jan '13 - 14:41 
2 years old can tell its disturbing the whole page
GeneralCOLSPAN="3" DOESN'T WORK IN FIREFOXmembermaorray8 Nov '10 - 0:59 
I've noticed it only works in IE, and in firefox it simply tries to insert the new line into the first only.
Is there a work around?
Rayman

GeneralRe: COLSPAN="3" DOESN'T WORK IN FIREFOXmemberStefan Bornemann18 Jun '12 - 8:30 
The animation is the problem in Firefox. Removing
 
.animate({
height: "140px",
opacity: 0.25,
}, 1000)
 
solves the problem.
GeneralMy vote of 1memberMember 10419927 Oct '10 - 9:08 
it is more cofusion for simple stuff
GeneralRe: My vote of 1memberjayantbramhankar18 Jun '11 - 0:20 
I think you didn't understand the code Smile | :)
GeneralMy vote of 5membershivasoft18 Aug '10 - 22:06 
Nice Article Jayant. Smile | :)
Very informative...
GeneralRe: My vote of 5memberjayantbramhankar23 Aug '10 - 3:37 
Thank you..Shivasoft
You are rocking with your blog..
GeneralMy vote of 5memberrameshvar18 Aug '10 - 9:15 
Great article....
I like it...
GeneralRe: My vote of 5memberjayantbramhankar18 Aug '10 - 9:30 
Thank you sir.
QuestionWhat about ScriptMethod?memberPetr Pechovic18 Aug '10 - 4:26 
why don't you use ScriptService, ScriptMethod and MS AJAX to call Web Service from JavaScript? You will be then able set up better security about exposing Web Services.
 
See more: http://msdn.microsoft.com/en-us/library/system.web.script.services.scriptmethodattribute.aspx[^]
 
Besides your example is sensitive for SQL Injection.
 
Petr
AnswerScriptMethod implementd.memberjayantbramhankar18 Aug '10 - 5:51 
Thanks alot for your valuable reply,
Now I have implemented Scriptservice in this article..
GeneralRe: ScriptMethod implementd.memberagorby18 Aug '10 - 9:00 
... and RowExpandCollpase.zip has lost. Wink | ;)
GeneralRe: ScriptMethod implementd.memberjayantbramhankar18 Aug '10 - 9:29 
Now it's downloadable.
GeneralMy vote of 5memberPranay Rana18 Aug '10 - 3:02 
its good
GeneralRe: My vote of 5memberjayantbramhankar18 Aug '10 - 3:28 
Thanks alot..

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130516.1 | Last Updated 18 Aug 2010
Article Copyright 2010 by jayantbramhankar
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid