Load HTML table with dynamic columns and Rows using jQuery

Load HTML table with dynamic columns and Rows using jQuery:

I have seen so many libraries to load a table with dynamic data. But most of them were demanding the column names for the table structure. But it is also possible to load the table with dynamic columns and dynamic rows with the async data.
I have tried the example in MVC. My goal here is to load the table with the data from the API which connects to database and fetch results. The query text, connection string values i am providing dynamically to the application. Like query text is in file and connection string in in java script file.

View Page:
@model IEnumerable<MvcApplication2.Controllers.Qry>

@{
    ViewBag.Title = "Home Page";
}

<div class="row">
                

   
    @foreach (var q in Model)
    { 
      
          <div class="col-lg-6 queryclass" id="@Guid.NewGuid()">
          <div class="panel panel-default">
          <div class="panel-heading"><span style="display:none">@Html.Raw(q.Query)</span>@q.QryHeader</div>
            <div class="panel-body">
                            <div class="table-responsive">
                                <table class="table table-striped table-bordered table-hover">
                <thead id="#thead"></thead>
                <tbody id="#tbody"></tbody>
            </table>
        </div> 
                </div>
              </div>
              </div>
    
       
    }
    </div> 

Controller Page:

 public ActionResult Index()
        {
           //process the files
            string path=HostingEnvironment.MapPath("~/Files/");
            string[] file=System.IO.Directory.GetFiles(path);
            ViewBag.Count = System.IO.Directory.GetFiles(path).Count();
            
            List<Qry> qrylist = new List<Qry>();
            foreach (var f in file)
            {
                //store file name and file text
                qrylist.Add(new Qry() { QryHeader=f.Substring(f.LastIndexOf("\\")+1,f.LastIndexOf(".")-f.LastIndexOf("\\")), Query=System.IO.File.ReadAllText(f)});
            }
            
            return View(qrylist);
        }

 public class Qry
    {
        public string QryHeader { get; set; }
        public string Query { get; set; }

    }

JavaScript : 
  
       $(document).ready(function () {
            

            $('.queryclass').each(function (index, elem) {
                var id = $(elem).attr("id");
                var qryval = $('#' + id + ' span').text();
                
                var constr = "Data Source=xx.xx.196.116,50000 ;database=<dbname>;integrated security=SSPI;Trusted_Connection=yes;connection timeout=48000";
                
               var qry = qryval.toString();// "select top 10 * from table1
                var qrytype = "sql";
                
                $.ajax({
                   //web api to make call with qry and connstr
                    url: "http://localhost:17406/api/values",
                    dataType: "json",
                    data: {"constr": constr, "qry":qry, "qrytype":qrytype},
                    type:'POST',
                    beforeSend: function () {
                        $('#' +id+ ' tbody').html('loading...');
                    }
                }).success(function (data) {

                    
                    var i = 1;
                    $('#' + id + ' tbody').html('loading...');
                    var thead = "<tr>";
                    $.each(JSON.parse(data), function (index, obj) {
                        var eachrow = "";
                        for (var name in obj) {
                            eachrow = eachrow + "<th>" + name + "</th>";

                        }
                        thead = thead + eachrow + "</tr>";
                        return false;
                    });
                    $('#' + id + ' thead').html(thead);

                    var tbody = "";

                    $.each(JSON.parse(data), function (index, obj) {
                        
                        var eachrow = "<tr>";
                        for (var name in obj) {

                            eachrow = eachrow
                                 
                                 + "<td>" + obj[name] + "</td>";

                            
                        }
                        tbody = tbody + eachrow + "</tr>";

                    });

                    $('#' + id + ' tbody').html(tbody);
                });
            });


            
        });

Web API that converts data table data into JSON :
I am getting the query results in datatable format. I am using this API call to convert / return JSON string so that we can use it for ajax calls.

  public string Post([FromBody]input inp)
        {
            QueryExecutorServiceReference.QueryExecutorClient client=new QueryExecutorServiceReference.QueryExecutorClient();
            
            
            DataTable dt = new DataTable("dt");
            if(inp.qrytype.ToLower()=="sql")
                dt = client.ExecuteSQLQuery(inp.qry, inp.constr);
            else
                dt = client.ExecuteOracleQuery(inp.qry, inp.constr);
            string JSONResult = "";
            JSONResult = JsonConvert.SerializeObject(dt);
            return JSONResult ;
        }

Comments

Popular posts from this blog

Base 64 encoding and decoding

LINQ Queries with GROUP BY, INNER JOIN, COUNT and SUM: Examples

How to write Custom delete Confirmation Modal for Kendo Grid in MVC: