Click here to Skip to main content
15,886,362 members
Articles / Web Development / ASP.NET

Row Expand Collapse using JQuery and Ajax

Rate me:
Please Sign up or sign in to vote.
4.45/5 (10 votes)
18 Aug 2010CPOL1 min read 85.9K   2.2K   34  
This article describes how to expand and collapse rows of a GridView or Table and showing data details using Jquery and Ajax
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="RowExpCol.aspx.cs" Inherits="RowExpCol" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ Import Namespace="System.Data" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link href="css/StyleSheet.css" rel="stylesheet" type="text/css" />
    <script src="js/jquery-1.4.2.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(document).ready(function() { 
        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
            trindex++;                                  //row index icreament to assign new row id everytime
            //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 anitmation to row
            var newRow = $("<tr id=tr"+ trindex + row).animate({ 
            height: "140px", 
            opacity: 0.25,
            }, 500);

          //adding row to existing table
         $(this).after(newRow);

         //getting previous created row
        var rowName="tr" + parseInt(trindex-1);

        //reomving previous created row from table with animation
        $("#"+rowName).find('td').removeClass('currRow').addClass('hideRow');
         $("#"+rowName).animate({ 
            height: "0px", 
            opacity: 0.25,
        }, 500, function() {
         $("#"+rowName).remove();
  });
         
   //ajax call to webservice
        $.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) {
                 //extrating response data to newly created row
                 $("#tr"+trindex ).find("td #did p #cost").text(msg.d.cost );
                 $("#tr"+trindex ).find("td #did  #des").text(msg.d.description); 
                 $("#tr"+trindex ).find("td #did #imagepath").attr('src', msg.d.imagePath); //$("#myImage").attr("src", "path/to/newImage.jpg");
                 },
                 error: FailedMessage     //showing error message if failure
             });
             }
        }); 
        
}); 
          function FailedMessage(result) {
              alert(result.status + ' ' + result.statusText);
          }  
    </script>
    <style type="text/css">
    .currRow
    {
        background-color:Blue;
        cursor:pointer;
        border-width:thin;
        border-color:Aqua;
        color:White;
        font-style:italic;
        font-size:medium;
    }   
    .hideRow
    {
        background-color:Red;
        cursor:pointer;
        border-width:thin;
        border-color:Blue;
        width: 100%;
        color:White;
        font-style:italic;
        font-size:medium;
    }
    
    </style>
</head>
<body>
    <form id="form1" runat="server"> 
    
<%
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
    SqlCommand cmd = new SqlCommand("SELECT [ProductId], [ProductName], [Category] FROM [Products]", con);
    con.Open();
    %>
  <table id="mytable" cellspacing="0" > 
  <caption>Row Expand/ Collapse using jquery/ajax  </caption> 
  <tr> 
    <th >Product Id</th> 
    <th>product Name</th> 
	<th>Category</th> 
  </tr> 
  <%
    SqlDataReader data = cmd.ExecuteReader();
    if (data.HasRows)
    {
        int i = 0;
        while(data.Read())
        {
            if (i % 2 == 0)
            {
            %>
            <tr>     
             <td><span><%=data[0].ToString()%></span></td> 
             <td><%=data[1].ToString()%></td> 
             <td><%=data[2].ToString()%></td> 
            </tr>
            <%
            }
            else
            {
            %>
            <tr>     
             <td class="alt"><span><%=data[0].ToString()%></span></td> 
             <td class="alt"><%=data[1].ToString()%></td> 
             <td class="alt"><%=data[2].ToString()%></td> 
            </tr>
            <%
            }
                i++;
        }
    }           
    con.Close();
  %>
</table>
    </form>
    </body>
</html>

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

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


Written By
Student
India India
I'm student (CE).

Comments and Discussions