Convert DataTable to generic list and display in HTML Table in ASP.Net MVC

malar
 
on Aug 12, 2021 10:59 PM
451 Views

Hi dharmendr,

Display Child Table record in modal popup on Parent record selection in ASP.Net MVC

Thanks for your reply. But still i have some complications to acheive this. You had classified with entities. But i am using Datatable to list.

But while clicking details button, modal popup showing with empty rows.

Kindly let me know where i missed to bind.

Thanks in Advance.

Here my code follows.

Model:

public class ProjectUpload
{
    public int GROUPNO { get; set; }
    public string ProjectCode { get; set; }
    public string ActivityCode { get; set; }
    public string Originatorname { get; set; }
    public string COMPANYCODE { get; set; }
    public List<ProjectUpload> ProjectUploadinfo { get; set; }
}

Controller:

List<ProjectUpload> projectlist = new List<ProjectUpload>();
if(dtPL.Rows.Count>0)
{
    for (int i = 0; i < dtPL.Rows.Count; i++)
    {
        projectlist.Add(new ProjectUpload
        {
            GROUPNO = Convert.ToInt32(dtPL.Rows[i]["GroupNo"].ToString()),
            ProjectCode = Convert.ToString(dtPL.Rows[i]["ProjectCode"].ToString()),
            ActivityCode = Convert.ToString(dtPL.Rows[i]["ActivityCode"].ToString()),
            Originatorname = Convert.ToString(dtPL.Rows[i]["BuyerName"].ToString()),
            COMPANYCODE = Convert.ToString(dtPL.Rows[i]["COMPANYCODE"].ToString().Trim()),
            ProjectUploadinfo = projectlist.Where(com => com.ProjectCode == dtPL.Rows[i]["ProjectCode"].ToString()).ToList(),
        }
    }
}
ViewBag.ProjectList = projectlist;

View:

<div class="table-responsive" style="overflow-x:scroll;">
<table id="tblHeader" class="table table-striped table-bordered table-hover" border="1" style="display:compact;" width="100%" cellspacing="0">
    <thead>
        <tr>
            <th>GroupNo</th>
            <th>ProjectCode</th>
            <th>Company Code</th>
            <th></th>
        </tr>
    </thead>
<tbody>
@if (ViewBag.ProjectList != null)
{
    foreach (var item in ViewBag.ProjectList)
    {
        <tr>
            <td><span>@item.GROUPNO</span></td>
            <td><span>@item.ProjectCode</span></td>
            <td><span>@item.CompanyCode</span></td>
            <td>
                <button type="button" class="btn btn-warning" data-toggle="modal" data-target="#@item.ProjectCode">Details</button>
                <div class="modal fade" id="@item.ProjectCode">
                    <div class="modal-dialog modal-dialog-centered">
                        <div class="modal-content">
                            <div class="modal-header">
                            <h4 class="modal-title">Details</h4>
                            <button type="button" class="close" data-dismiss="modal">&times;</button>
                        </div>
                        <div class="modal-body">
                            <table class="table">
                                <tr>
                                    <th>Activity Code</th>
                                    <th>Buyer Name</th>
                                </tr>
                                <tbody>
                                @foreach (AAF.Models.ProjectUpload order in item.ProjectUploadinfo)
                                {
                                     <tr>
                                     <td>@order.ActivityCode</td>
                                     <td>@order.BuyerName</td>
                                     </tr>
                                 }
                                 </tbody>
                             </table>
                         </div>
                         <div class="modal-footer">
                             <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                         </div>
                     </div>
                 </div>
             </div>
         </td>
    </tr>
    }
}
</tbody>
</table>
</div>

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
dharmendr
 
on Aug 13, 2021 04:32 AM

Hi malar,

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

Model

public class CustomerModel
{
    public string CustomerID { get; set; }
    public string ContactName { get; set; }
    public string City { get; set; }
    public List<Order> Orders { get; set; }
}

Namespaces

using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Reflection;

Controller 

public class HomeController : Controller
{
    // GET: Home
    public ActionResult Index()
    {
        DataTable dtCustomers = GetData("SELECT TOP 5 * FROM Customers");
        DataTable dtOrders = GetData("SELECT * FROM Orders");
        List<CustomerModel> model = new List<CustomerModel>();
        for (int i = 0; i < dtCustomers.Rows.Count; i++)
        {
            DataRow[] dr = dtOrders.Select("CustomerID='" + dtCustomers.Rows[i]["CustomerID"].ToString() + "'");
            model.Add(new CustomerModel
            {
                CustomerID = dtCustomers.Rows[i]["CustomerID"].ToString(),
                ContactName = dtCustomers.Rows[i]["ContactName"].ToString(),
                City = dtCustomers.Rows[i]["City"].ToString(),
                Orders = dr.Length > 0 ? ConvertDataTableToList<Order>(dr.CopyToDataTable()).Take(5).ToList() : new List<Order>()
            });
        }

        ViewBag.ProjectList = model;
        return View();
    }

    private DataTable GetData(string query)
    {
        string conString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
        using (SqlConnection con = new SqlConnection(conString))
        {
            SqlCommand cmd = new SqlCommand(query);
            using (SqlDataAdapter sda = new SqlDataAdapter())
            {
                cmd.Connection = con;
                sda.SelectCommand = cmd;
                using (DataTable dt = new DataTable())
                {
                    sda.Fill(dt);
                    return dt;
                }
            }
        }
    }

    public static List<T> ConvertDataTableToList<T>(DataTable dt)
    {
        const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
        var columnNames = dt.Columns.Cast<DataColumn>()
            .Select(c => c.ColumnName)
            .ToList();
        var objectProperties = typeof(T).GetProperties(flags);
        var targetList = dt.AsEnumerable().Select(dataRow =>
        {
            var instanceOfT = Activator.CreateInstance<T>();

            foreach (var properties in objectProperties
            .Where(properties => columnNames.Contains(properties.Name) && dataRow[properties.Name] != DBNull.Value))
            {
                properties.SetValue(instanceOfT, dataRow[properties.Name], null);
            }
            return instanceOfT;
        }).ToList();

        return targetList;
    }
}

View

@using Nested_Data_ModalPopup_MVC.Models
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" />
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
</head>
<body>
    <table class="table">
        <tr>
            <th>Customer Id</th>
            <th>Name</th>
            <th>City</th>
            <th>Orders</th>
        </tr>
        <tbody>
            @foreach (CustomerModel customer in ViewBag.ProjectList)
            {
                <tr>
                    <td>@customer.CustomerID</td>
                    <td>@customer.ContactName</td>
                    <td>@customer.City</td>
                    <td>
                        <button type="button" class="btn btn-primary" data-toggle="modal"
                                data-target="#@customer.CustomerID">
                            View
                        </button>
                        <div class="modal fade" id="@customer.CustomerID">
                            <div class="modal-dialog modal-dialog-centered">
                                <div class="modal-content">
                                    <div class="modal-header">
                                        <h4 class="modal-title">Order Details</h4>
                                        <button type="button" class="close" data-dismiss="modal">&times;</button>
                                    </div>
                                    <div class="modal-body">
                                        <table class="table">
                                            <tr>
                                                <th>Order Id</th>
                                                <th>Freight</th>
                                            </tr>
                                            <tbody>
                                                @foreach (Order order in customer.Orders)
                                                {
                                                    <tr>
                                                        <td>@order.OrderID</td>
                                                        <td>@order.Freight</td>
                                                    </tr>
                                                }
                                            </tbody>
                                        </table>
                                    </div>
                                    <div class="modal-footer">
                                        <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </td>
                </tr>
            }
        </tbody>
    </table>
</body>
</html>

Screenshot