Create Dynamic Table In JavaScript Using WebMethod And jQuery AJAX Without Postback

Create HTML table from AJAX, JSON

In the world of rapidly evolving technologies people are doing great things in terms of user experience in websites. Gone are the days when people used to write every single code piece on server side and frequents postbacks were seen. Today we will learn how to create dynamic tables using jquery ajax using data from server side in the form of json object. The good thing will be that all would be done without having a postback.



What we will learn:

  • Some basic HTML structure for table
  • Jquery ajax syntax
  • Creation of WebMethod for ajax call
  • Using JSON object

What we need to know already:

  • Basic .Net (Here I will be using C# but you can have your way in VB .Net as well)
  • Basic JQuery Selector
  • Basic JavaScript

First create an aspx page where you need to create dynamic table. Place a table with an id given to it.
Your code will look something like this

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Test" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
 <title>Dynamic Table</title>

<--**Below is the reference for JQuery as it will be needed for the ajax call and table creation**-->
 <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>

 <script> 
 <!-- MAGIC HAPPENS HERE-->
 </script>
</head>
<body>
 <form id="form1" runat="server">
 <div>
 <table id="tblDynamic"></table>
 </div>
 </form>
</body>
</html>


Now we need to add script for ajax call which will bring the data in JSON format to be populated in table.

$.ajax({
 method: "POST",
 url: applicationURL + "Test.aspx/GetDynamicRows",
 data: '{rowcount: "' + 10 + '" }',
 contentType: "application/json; charset=utf-8",
 dataType: "json",
 success: function (data) {
  //Code for table creation
 }
});


As you can see in the url property of ajax call we have used the page name Test.aspx and following it is the name of the WebMethod which is to be called on code behind Test.aspx.cs. Let's now see the code for writing the webmethod.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    /// <summary>
    /// This method returns a list of type row having the values for columns.
    /// </summary>
    /// <param name="rowcount">Its used to specify the number of rows to return</param>
    [System.Web.Services.WebMethod] //This webattribute is used to specify that its a webmethod
    //public and static keywords are used here so that the javascript can access this method without any restriction
    public static List<row> GetDynamicRows(int rowcount)
    {
        List<row> lstRows = new List<row>();
        for (int i = 1; i <= rowcount; i++)
        {
            row rw = new row();
            rw.Col1 = "Row " + i + " Column 1";
            rw.Col2 = "Row " + i + " Column 2";
            rw.Col3 = "Row " + i + " Column 3";
            lstRows.Add(rw);
        }
        return lstRows;
    }

    public class row
    {
        public string Col1 { get; set; }
        public string Col2 { get; set; }
        public string Col3 { get; set; }
    }
}

Now lets put some code into the success function of ajax call. Here we will put in some code to create html structure of the table using tr (row) & td (column) tags.

Response of Ajax call in JSON format

success: function (data) {
 //Code for table creation
 var jsonObj = data.d; //For storing the response data in jsonObj variable.
 var strHTML = '';
 $(jsonObj).each(function(){
  var row= $(this)[0]; //Extracting out row object one by one.
  strHTML += '<tr><td>' + row["Col1"] + '</td><td>'+ row["Col2"] 
                          + '</td><td>'+ row["Col3"] + '</td></tr>'; 
                          //Above code is for creating the html part of the table.
 });
 $('#tblDynamic').append(strHTML);//To append the html part into the table     
 }

Now when all being done you can have your table ready and your aspx page will look like this.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Test" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Dynamic Table</title>
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
    <style>
        #tblDynamic td{border:1px solid grey;} /*Style added to show the actual structure of table*/
    </style>
    <script> 
        $.ajax({
            method: "POST",
            url: "Test.aspx/GetDynamicRows",
            data: '{rowcount: "' + 10 + '" }',
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (data) {
                var jsonObj = data.d; //For storing the response data in jsonObj variable.
                var strHTML = '';
                $(jsonObj).each(function(){
                    var row = $(this)[0]; //Extracting out row object one by one.
                    strHTML += '<tr><td>' + row["Col1"] + '</td><td>'+ row["Col2"] + '</td><td>'
                                + row["Col3"] + '</td></tr>'; //For creating the html part of the table
                });
                $('#tblDynamic').append(strHTML);//To append the html part into the table               
            },
            error:function()
            {
                alert('some error occurred');
            }
        });
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <table id="tblDynamic"></table>
    </div>
    </form>
</body>
</html>
And the output would be like this:

This is the generated html table by the code

Although the output isn't pretty but you can modify its appearance by using some css.
And in the similar way you can dynamically create any html element like list or even bind a dropdown. So this is it about creating html table using JQuery, Ajax and .Net. Feel free to write your queries and any suggestions that you have.


We have a made a video for this post, have a look. You will learn it better.





Happy Learning!!!

Comments

Popular posts from this blog

Create Android Apps - Getting Started

Polymorphism in Kotlin With Example