Introduction
In this tip, I am going to write about Expandable table using Ajax post method. I have used
Div
having name "tblUsers"
to append using jQuery Ajax post method.
Let's see further in detail about that.
Background
In this tip, all the users data has been structured in gridview form.
Using Ajax post method, all user's data is retrieved and set to
Div
using jQuery.
It is very fast and smooth during expansion and there is no need for any other third party DLLs or setups.
Using the Code
I have implemented code here. There is only one page for making an expandable table. It is very easy and fast.
First, create a database named DemoDatabase in your SQL Server and that runs that script in your SQL server (only for this demo purpose, you can integrate your own database in this demo)
CREATE TABLE [dbo].[Users](
[id] [int] IDENTITY(1,1) NOT NULL,CREATE TABLE [dbo].[Users](
[FirstName] [varchar](50) NULL,
[LastName] [varchar](50) NULL,
[UserName] [varchar](50) NULL,
[Email] [nvarchar](150) NULL,
[imageURL] [nvarchar](max) NULL,
PRIMARY KEY CLUSTERED
(
[id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, _
ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
SET IDENTITY_INSERT [dbo].[Users] ON
GO
INSERT [dbo].[Users] ([id], [FirstName], [LastName], [UserName], [Email], _
[imageURL]) VALUES (1, N'Nirav', N'Prabtani', N'Nills', _
N'niravjprabtani@gmail.com', N'nirav.jpg')
GO
INSERT [dbo].[Users] ([id], [FirstName], [LastName], [UserName], [Email], _
[imageURL]) VALUES (2, N'Rajan', N'Mrug', N'Raj', _
N'Raj@gmail.com', N'rajan.jpg')
GO
INSERT [dbo].[Users] ([id], [FirstName], [LastName], [UserName], [Email], _
[imageURL]) VALUES (3, N'Rajesh', N'Saradhara', N'Rajesh', _
N'rajesh@yahoo.in', N'rajesh.jpg')
GO
INSERT [dbo].[Users] ([id], [FirstName], [LastName], [UserName], [Email], _
[imageURL]) VALUES (4, N'Dharmendra', N'Pansara', _
N'Dhamo', N'Dhamo@hotmail.com', N'demo.jpg')
GO
SET IDENTITY_INSERT [dbo].[Users] OFF
GO
Now create WebForm IndexTable in your project.
1) IndexTable.aspx
- Javascript Code
Put Javascript js link like jQuery.1.4.1.min.js or other..... :)
$(document).ready(function () {
$(document).ready(function () {
//Call BindUsers function during Page load
BindUsers();
});
//Bind all data to div using ajax Post method
function BindUsers() {
$.ajax({
type: 'POST', // Method type
url: 'IndexTable.aspx/GetUsers', //Page URL/Function Name
data: {}, //Parameters
contentType: 'application/json',
dataType: 'json',
success: function (data) { //Returned data
if (data.d.length > 0) { //Check Count of data
// Set Div to empty.
$("#tblUsers").empty();
//Create Header of a Tbale
$("#tblUsers").append("<tr class='trHead'
><td class='tdHead'>Firstname</td>
<td class='tdHead'>Lastname</td>
<td class='tdHead'>Username</td></tr>");
//Bind Div in tabular form using For loop
for (var i = 0; i < data.d.length; i++) {
$("#tblUsers").append("<tr
onclick='ExpandGrid(" + data.d[i].id + ")' >
<td class='tdHead'>" + data.d[i].FirstName + "
</td><td class='tdHead'>" + data.d[i].LastName + "
</td><td class='tdHead'>" + data.d[i].UserName + "
</td></tr><tr style='display:none;background-color:#F2F2F2'
id='trExpand" + data.d[i].id + "'><td valign='middle'
align='center' ><img src='Images/" + data.d[i].ImageURL +
"' height='80px' width='50px'></td>
<td colspan='2' align='center' valign='middle'>
<table><tr><td><input id='txtFirstName" +
data.d[i].id + "' value=" + data.d[i].FirstName + " >
</td></tr><td><input id='txtLastName" +
data.d[i].id + "' value=" + data.d[i].LastName + " >
</td><tr><td><input id='txtUserName" + data.d[i].id +
"' value=" + data.d[i].UserName + " ></td></tr>
<tr><td><input id='txtEmail" + data.d[i].id + "'
value=" + data.d[i].Email + " ></td></tr></table>
</td> </tr>");
}
}
},
error: function (result) { //Call on failure or error
alert(result.d);
}
});
}
//Function for expansion of a table
function ExpandGrid(id) {
$("#trExpand" + id).toggle(300);
}
- CSS Styles
.trHead
{
height: 30px;
background-color: #c8c8c8;
color: White;
font-weight: bold;
}
.tdHead
{
width: 150px;
border: 1px solid #c8c8c8;
height: 30px;
vertical-align: middle;
padding-left: 5px;
cursor: pointer;
}
.trExpand
{
border: 1px solid #c8c8c8;
}
- HTML Code
<div id="tblUsers"></div>
2) IndexTable.aspx.cs
using System;
using System.Collections.Generic;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Data.SqlClient;
using System.Configuration;
using System.Data;
namespace ExpandableTable
{
public partial class IndexTable : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
// Get All users data
[WebMethod]
public static Users[] GetUsers()
{
// Create Object of a list
List<Users> Details = new List<Users>();
//Select All users data from SQL database
string SelectUsers = "select * from Users";
SqlConnection cn = new SqlConnection
(ConfigurationManager.ConnectionStrings["cs_Users"].ConnectionString);
SqlCommand cmd = new SqlCommand(SelectUsers, cn);
cn.Open();
cmd.ExecuteNonQuery();
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dtUsers = new DataTable();
da.Fill(dtUsers);
//Insert all users data into LIST
foreach (DataRow dtrow in dtUsers.Rows)
{
Users Dataobj = new Users();
Dataobj.id = Convert.ToInt32(dtrow["id"]);
Dataobj.FirstName = dtrow["FirstName"].ToString();
Dataobj.LastName = dtrow["LastName"].ToString();
Dataobj.UserName = dtrow["UserName"].ToString();
Dataobj.Email = dtrow["Email"].ToString();
Dataobj.ImageURL = dtrow["imageURL"].ToString();
Details.Add(Dataobj);
}
//Return array value to bind data
return Details.ToArray();
}
//Class of users
public class Users
{
public int id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string UserName { get; set; }
public string Email { get; set; }
public string ImageURL { get; set; }
}
}
}
In this manner Div "
tblUsers
" has been bound using Ajax Post method like Expandable table.How Does It Work??
When application is started, first of all, jQuery page load method occurs and using Ajax post method
WebMethod GetUsers()
is called and all users data from database returned in array format using Users
class.
We can
struct Div
using append jQuery syntax.
In this example, there are two
tags that have been initialized in Div, one is visible and the second is invisible using CSS property "display:block
".
When
Div
will bind, it will look like that:
There are four
Users
, therefore there are four columns in a table.
Now if you click on any column of a table, then the second row which is already invisible is set to visible by calling JavaScript function
function ExpandGrid(id) {
$("#trExpand" + id).toggle(300);ExpandGrid():
function ExpandGrid(id) {
}
and it will look like...
Points of Interest
I have designed it in a very simple form. You can modify by simply assigning styles or classes.
We can also put up and down arrows for expanding functionality.
We can apply transition effects using jQuery during expansion of table.
History
- 27th March 2014: Initial post
- See original Article at
Nice one.
ReplyDeleteThank you.
Deleteamazing boss
ReplyDeleteHello, please, send me the code to my email andres.morante@gmail.com, for some reason it does not work, I need the example.
ReplyDeleteThank you,
Andres de Lima, Peru, South America