Bind (Populate) Nested HTML Table with Expand All and Collapse All using WebService in AngularJS

Last Reply 3 months ago By dharmendr

You are viewing reply posted by: dharmendr 3 months ago.
Posted 3 months ago

Hi rani,

Check this example. Now please take its reference and correct your code.

Database

For this example I have used of Northwind database that you can download using the link given below.

Download Northwind Database

HTML

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Expand Collapse All HTML Table AngularJS</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
    <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.8/angular.min.js"></script>
    <script type="text/javascript">
        var app = angular.module('MyApp', [])
        app.controller('MyController', function ($scope, $http) {
            $http.post("WebServiceCS.asmx/GetCustomerOrders", { 'Content-Type': 'application/json' })
            .then(function (response) {
                $scope.Customers = response.data.d;
            });

            $scope.ExpandAll = function (expanded) {
                $scope.$broadcast('onExpandAll', {
                    expanded: expanded
                });
            };

        })
        app.directive('expand', function () {
            function link(scope, element, attrs) {
                scope.$on('onExpandAll', function (event, args) {
                    scope.expanded = args.expanded;
                });
            }
            return { link: link };
        });
    </script>
</head>
<body ng-app="MyApp" ng-controller="MyController">
    <table class="table table-condensed table-bordered">
        <thead>
            <tr class="success">
                <th>
                    <button type="button" ng-click="ExpandAll(allExpanded = !allExpanded)" class="btn btn-default">
                        <span ng-bind="allExpanded ? '-' : '+'"></span>
                    </button>
                </th>
                <th>Customer ID</th>
                <th>Name</th>
                <th>Country</th>
            </tr>
        </thead>
        <tbody>
            <tr ng-repeat-start="customer in Customers">
                <td>
                    <button ng-click="expanded = !expanded" expand class="btn btn-default">
                        <span ng-bind="expanded ? '-' : '+'"></span>
                    </button>
                </td>
                <td>{{customer.CustomerId}}</td>
                <td>{{customer.Name}}</td>
                <td>{{customer.Country}}</td>
            </tr>
            <tr ng-repeat-end ng-show="expanded" class="sub">
                <td>
                </td>
                <td colspan="5">
                    <table class="table table-condensed table-bordered">
                        <thead>
                            <tr>
                                <th>Order Id</th>
                                <th>Freight</th>
                                <th>Ship City</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr ng-repeat="order in customer.Orders">
                                <td>{{order.OrderId}}</td>
                                <td>{{order.Freight}}</td>
                                <td>{{order.ShipCity}}</td>
                            </tr>
                        </tbody>
                    </table>
                </td>
            </tr>
        </tbody>
    </table>
</body>
</html>

Webservice

C#

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.SqlClient;
using System.Web.Services;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. 
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
    [WebMethod]
    public List<Customer> GetCustomerOrders()
    {
        List<Customer> customers = new List<Customer>();
        using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.Connection = con;
                con.Open();
                cmd.CommandText = "SELECT TOP 5 CustomerId,ContactName,Country FROM Customers ORDER BY ContactName ASC";
                SqlDataReader rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    Customer customer = new Customer
                    {
                        CustomerId = rdr["CustomerId"].ToString(),
                        Name = rdr["ContactName"].ToString(),
                        Country = rdr["Country"].ToString(),
                        Orders = Orders(rdr["CustomerId"].ToString())
                    };

                    customers.Add(customer);
                }
                con.Close();
            }
        }

        return customers;
    }

    public List<Order> Orders(string customerId)
    {
        List<Order> orderList = new List<Order>();
        using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString))
        {
            using (SqlCommand cmd = new SqlCommand())
            {
                cmd.Connection = con;
                con.Open();
                cmd.CommandText = "SELECT TOP 3 OrderId,Freight,ShipCity FROM Orders WHERE CustomerId = @CustomerId";
                cmd.Parameters.AddWithValue("@CustomerId", customerId);
                SqlDataReader rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    Order order = new Order
                    {
                        OrderId = Convert.ToInt32(rdr["OrderId"]),
                        Freight = Convert.ToDecimal(rdr["Freight"]),
                        ShipCity = Convert.ToString(rdr["ShipCity"]),
                    };
                    orderList.Add(order);
                }
                con.Close();
            }
        }

        return orderList;
    }

    public class Customer
    {
        public string CustomerId { get; set; }
        public string Name { get; set; }
        public string Country { get; set; }
        public List<Order> Orders { get; set; }
    }

    public class Order
    {
        public int OrderId { get; set; }
        public decimal Freight { get; set; }
        public string ShipCity { get; set; }
    }
}

VB.Net

Imports System.Web
Imports System.Collections.Generic
Imports System.Configuration
Imports System.Data.SqlClient
Imports System.Web.Services

' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="http://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class WebService
    Inherits System.Web.Services.WebService
    <WebMethod()>
    Public Function GetCustomerOrders() As List(Of Customer)
        Dim customers As List(Of Customer) = New List(Of Customer)()
        Using con As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("constr").ConnectionString)
            Using cmd As SqlCommand = New SqlCommand()
                cmd.Connection = con
                con.Open()
                cmd.CommandText = "SELECT TOP 5 CustomerId,ContactName,Country FROM Customers ORDER BY ContactName ASC"
                Dim rdr As SqlDataReader = cmd.ExecuteReader()
                While rdr.Read()
                    Dim customer As Customer = New Customer With {
                        .CustomerId = rdr("CustomerId").ToString(),
                        .Name = rdr("ContactName").ToString(),
                        .Country = rdr("Country").ToString(),
                        .Orders = Orders(rdr("CustomerId").ToString())
                    }
                    customers.Add(customer)
                End While
                con.Close()
            End Using
        End Using

        Return customers
    End Function

    Public Function Orders(ByVal customerId As String) As List(Of Order)
        Dim orderList As List(Of Order) = New List(Of Order)()
        Using con As SqlConnection = New SqlConnection(ConfigurationManager.ConnectionStrings("constr").ConnectionString)
            Using cmd As SqlCommand = New SqlCommand()
                cmd.Connection = con
                con.Open()
                cmd.CommandText = "SELECT TOP 3 OrderId,Freight,ShipCity FROM Orders WHERE CustomerId = @CustomerId"
                cmd.Parameters.AddWithValue("@CustomerId", customerId)
                Dim rdr As SqlDataReader = cmd.ExecuteReader()
                While rdr.Read()
                    Dim order As Order = New Order With {
                        .OrderId = Convert.ToInt32(rdr("OrderId")),
                        .Freight = Convert.ToDecimal(rdr("Freight")),
                        .ShipCity = Convert.ToString(rdr("ShipCity"))
                    }
                    orderList.Add(order)
                End While

                con.Close()
            End Using
        End Using

        Return orderList
    End Function

    Public Class Customer
        Public Property CustomerId As String
        Public Property Name As String
        Public Property Country As String
        Public Property Orders As List(Of Order)
    End Class

    Public Class Order
        Public Property OrderId As Integer
        Public Property Freight As Decimal
        Public Property ShipCity As String
    End Class
End Class

Screenshot