How to view table data in Select list changes

jewel 901 Reputation points
2023-09-10T16:00:01.04+00:00

I am a bit confused about my work. When receiving data from View Bag the task I am doing is working. But facing problem while changing select list. If any experienced would help me. I would benefit. thanks in advance.



public IActionResult Index()
        {
            var porlist = _context.tbl_Products.ToList();

            return View(porlist);
        }
      
        public JsonResult GetProductRecord()
        {
            string query = "Select * from tbl_Products";
            var List = _context.tbl_Products.FromSqlRaw(query);
           ViewBag.listdata= List;
            return Json(List);

        }
@*index.cshtml*@
@model IEnumerable<aspCoreProject.Models.tbl_Product>
<button id="add" onclick="addata()" class="btn btn-primary">save Data</button>
<table class="mdl-data-table" id="MyDataTable">
  <thead>
        <tr>
            <th>
                allproduct
            </th>
            <th >
                id
            </th>
            <th>
                name
            </th>
            <th>
              rate
            </th>
            <th >
                Qty
            </th>
           
            <th>
               
            </th>
        </tr>
    </thead>
        @foreach (var item in Model)
        {
            <tr>
                <td><input type="checkbox" name="Selectone" class="chk_isChecked" id="@item.ProductID" /></td>
                <td>@item.ProductID </td>
                
                <td>@item.ProductName</td>
            <td><label>@item.PurchaseRate</label> </td>
            <td><input type="number" value="" min="1" onkeypress="return isNumberKey(event)" class="txt_qty" /></td>

            <td>'<label></label>'</td>
            </tr>
}
    <tfoot>
        <tr>
            <td></td>
             <td></td>
            <td></td>
            <td></td>
            
            <td>Total Value :</td>

            <td> </td>
        </tr>
    </tfoot>
    
</table>
<script>

    $(function () {
        debugger
        $(".txt_qty").on("input", function () {
            var total = 0;
            $("table.mdl-data-table tbody tr").each(function (i, tr) {
                debugger
                var $tds = $(tr).find('td');
                if ($tds.length > 0) {
                    var c1 = Number($($tds[3]).find("label").text());
                    var c2 = Number($($tds[4]).find("input").val());
                    val = (c1 > 0 && c2 > 0) ? c1 * c2 : 0;
                    $($tds[5]).find("label").text(val);
                    total += val;
                }
            });
            $("table.mdl-data-table tfoot tr td")[5].innerHTML = total
        }).trigger("input");
    });
    $(function () {
        debugger
        $(".txt_qty").each(function (index, item) {
            var txtvalue = $(item).val();
            if (txtvalue.length > 0 && txtvalue != "0") {
                $(item).closest("tr").find(".chk_isChecked").prop('checked', true);
            }
            else {
                $(item).closest("tr").find(".chk_isChecked").prop('checked', false);
            }
            $(item).change(function () {
                var currentvalue = $(this).val();
                if (currentvalue.length > 0 && currentvalue != "0") {
                    $(this).closest("tr").find(".chk_isChecked").prop('checked', true);
                }
                else {
                    $(this).closest("tr").find(".chk_isChecked").prop('checked', false);
                }
            })
        })
    })
   
</script>

useing Selectlist project. Prolem here

    public class Purchaseproductvm
    {
        [Key]
        public int productID { get; set; }
        public int CompanyID { get; set; }
      
        public String Compnay_Name { get; set; }
        public String product_name { get; set; }
       
        public decimal purchaseRate { get; set; }
     

    }
}
  public JsonResult GetProductRecord(int companyid)
        {

            var CompnayName = "a.CompanyID";
            var Compnayvalue = companyid;


            string query = $"Select a.productID,a.CompanyID,b.Compnay_Name,a.product_name,a.purchaseRate\r\nfrom tbl_Products a \r\njoin tbl_Compnays b \r\non a.CompanyID=b.Company_ID where {CompnayName}={Compnayvalue}";
            var List = _context.purchaseproductvms.FromSqlRaw(query);
  
            return Json(List);
        }
        public JsonResult vendername()
        {
            var venders = _context.tbl_Venders.ToList();

            return Json(venders);
        }
 public JsonResult Compnayname(int id)
        {
            var compnay = _context.tbl_Compnays.Where(x => x.vender_ID == id).ToList();
            return Json(compnay);
        }

@*index.cshtml*@
<style type="text/css">
	#blogTable {
		border-collapse: collapse;
		border: 1px solid black;
	}
		#blogTable th, #blogTable td {
			border: 1px solid black;
			padding: 8px;
		}
</style>

<select class="" id="VenderDrop">
	<option value="0">---Select Vender Name----</option>
</select>
<select class="" id="CompanyDrop">
	<option value="0">---Select Company Name----</option>
</select>



<table id="blogTable" class="zui-table zui-table-rounded">
	<thead>
		<tr>
			<th>Product ID</th>
			<th>Company Name</th>
			<th>Product Name</th>
			<th>Purchase Rate</th>
			<th>Qty</th>
			<th>value</th>
			<th>Checkbox</th>
		</tr>
	</thead>
	<tbody></tbody>
	<tfoot>
		<tr>
			<td></td>
			<td>Total Value :</td>

			<td> </td>
		</tr>
	</tfoot>
</table>

<script>
	$(document).ready(function () {

		GetvenderSelectList();

		$('#VenderDrop').change(function () {
			var id = $(this).val();
			$('#CompanyDrop').empty();
			$('#CompanyDrop').append('<option>---Select Company Name----</option>');

			$.ajax({
				url: '/test/Compnayname?id=' + id,
				success: function (result) {
					$.each(result, function (i, data) {
						$('#CompanyDrop').append('<option value=' + data.company_ID + '>' + data.compnay_Name + '</option>');

					});
				}
			});
		});
	})
	function GetvenderSelectList() {
		$.ajax({
			url: '/test/vendername',
			success: function (result) {
				$.each(result, function (i, data) {
					$('#VenderDrop').append('<option value=' + data.vender_ID + '>' + data.vender_Name + '</option>');

				});
			}
		});
	}
	$("#CompanyDrop").change(function () {
		$.ajax({
			url: '/Purchase/GetProductRecord',
			type: 'Get',
			datatype: JSON,
			data: {
				companyid: $("#CompanyDrop").val()
			},
			success: function (data) {

				$('#blogTable tbody').empty();

				$.each(data, function (i, item) {

					var rows = "<tr>"
						+ "<td>" + item.productID + "</td>"
						+ "<td>" + item.compnay_Name + "</td>"
						+ "<td>" + item.product_name + "</td>"
						+ "<td>" +'<label>'+item.purchaseRate+'</label>'+ "</td>"
						+ "<td>" +'<input type="number" value="" min="1" onkeypress="return isNumberKey(event)" class="txt_qty" />'+ "</td>"
						+ "<td>"+'<label ></label>'+"</td>"
						+ "<td>"+'<input type="checkbox" name="Selectone" class="chk_isChecked" id="item.productID" />'+"</td>"
						+ "</tr>";
					$('#blogTable tbody').append(rows);
				});
			}
		});

	});

	$(function () {
		debugger
		$(".txt_qty").each(function (index, item) {
			debugger
			var txtvalue = $(item).val();
			if (txtvalue.length > 0 && txtvalue != "0") {
				$(item).closest("tr").find(".chk_isChecked").prop('checked', true);
			}
			else {
				$(item).closest("tr").find(".chk_isChecked").prop('checked', false);
			}
			$(item).change(function () {
				var currentvalue
					= $(this).val();
				if (currentvalue.length > 0 && currentvalue != "0") {
					$(this).closest("tr").find(".chk_isChecked").prop('checked', true);
				}
				else {
					$(this).closest("tr").find(".chk_isChecked").prop('checked', false);
				}
			})
		})
	})
	$(function () {
		debugger
		$(".txt_qty").on("input", function () {
			var total = 0;
			$("table.mdl-data-table tbody tr").each(function (i, tr) {
				debugger
				var $tds = $(tr).find('td');
				if ($tds.length > 0) {
					var c1 = Number($($tds[3]).find("label").text());
					var c2 = Number($($tds[4]).find("input").val());
					val = (c1 > 0 && c2 > 0) ? c1 * c2 : 0;
					$($tds[5]).find("label").text(val);
					total += val;
				}
			});
			$("table.mdl-data-table tfoot tr td")[5].innerHTML = total
		}).trigger("input");
	});

</script>


ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,560 questions
0 comments No comments
{count} votes

Accepted answer
  1. JasonPan - MSFT 5,551 Reputation points Microsoft Vendor
    2023-09-15T09:10:03.2266667+00:00

    Hi @jewel,

    Here is my test result:

    BlazorApp1

    Sample Code

    @{
        ViewData["Title"] = "How to add html input textbox, label, checkbox to jqery table";
    }
    
    <style>
        #blogTable {
            border-collapse: collapse;
            border: 1px solid black;
        }
    
            #blogTable th, #blogTable td {
                border: 1px solid black;
                padding: 8px;
            }
    </style>
    
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    
    <script>
        $(document).ready(function () {
    
            // init data
            loadData();
            $("#CompanyDrop").change(function () {
                var companyid = $("#CompanyDrop").val();
                loadData(companyid);
            });
    
            $("#productForm").submit(function (e) {
                e.preventDefault();
    
                var products = [];
    
                $("#blogTable tbody tr:not(.total-row)").each(function () {
                    var product = {
                        productID: $(this).find("td:eq(0)").text(),
                        productName: $(this).find("td:eq(1)").text(),
                        purchaseRate: $(this).find("td:eq(2) label").text(),
                        qty: ($(this).find("td:eq(3) input").val() == "") ? 0 : $(this).find("td:eq(3) input").val(),
                        totalValue: parseInt($(this).find("td:eq(2) label").text()) * (($(this).find("td:eq(3) input").val() == "") ? 0 : $(this).find("td:eq(3) input").val()),
                        isChecked: $(this).find("td:eq(5) input").prop("checked")
                    };
                    products.push(product);
                });
    
                //...[Ajax call remains unchanged]
            });
    
        })
    
        function loadData(companyid) {
            $.ajax({
                url: companyid == undefined ? ('/Purchase/GetProductRecord?companyid=-1') : ('/Purchase/GetProductRecord?companyid=' + companyid),
                type: 'Get',
                datatype: 'json',
                success: function (data) {
                    $('#blogTable tbody').empty();
                    $.each(data, function (i, item) {
                        var rows = "<tr>"
                            + "<td>" + item.productID + "</td>"
                            + "<td>" + item.productName + "</td>"
                            + "<td><label>" + item.purchaseRate + "</label></td>"
                            + "<td><input type='number' value='' min='1' onkeypress='return isNumberKey(event)' class='txt_qty' data-rate='" + item.purchaseRate + "'/></td>"
                            + "<td><label class='total-value'></label></td>"
                            + "<td><input type='checkbox' name='Selectone' class='chk_isChecked' id='" + item.productID + "'/></td>"
                            + "</tr>";
                        $('#blogTable tbody').append(rows);
                    });
    
                    // After loading data, initialize checkbox status based on qty values
                    $('#blogTable tbody .txt_qty').each(function () {
                        var qty = $(this).val();
                        if (qty && parseInt(qty) > 0) {
                            $(this).closest("tr").find(".chk_isChecked").prop("checked", true);
                        }
                    });
    
                    bindEvents();
                }
            });
        }
    
        function bindEvents() {
            $(".txt_qty").off("input").on("input", function () {
                var rate = $(this).data("rate");
                var qty = $(this).val();
                var total = rate * qty;
                $(this).closest("tr").find(".total-value").text(total);
    
                // Check if qty has a value and is greater than 0, then check the checkbox
                if (qty && parseInt(qty) > 0) {
                    $(this).closest("tr").find(".chk_isChecked").prop("checked", true);
                } else {
                    $(this).closest("tr").find(".chk_isChecked").prop("checked", false);
                }
    
                calculateTotalValue();
            });
    
            $(".chk_isChecked").off("change").on("change", function () {
                calculateTotalValue();
            });
    
            calculateTotalValue();
        }
    
        function calculateTotalValue() {
            var totalValue = 0;
            $("#blogTable tbody tr:not(.total-row)").each(function () {
                if ($(this).find(".chk_isChecked").prop("checked")) {
                    var value = $(this).find(".total-value").text();
                    totalValue += (value === "" ? 0 : parseInt(value));
                }
            });
            $(".total-sum").text(totalValue);
        }
    
        function isNumberKey(evt) {
            var charCode = (evt.which) ? evt.which : evt.keyCode;
            if (charCode > 31 && (charCode < 48 || charCode > 57))
                return false;
            return true;
        }
    </script>
    
    <form id="productForm" method="post" action="/Purchase/SubmitProducts">
        <select class="" id="VenderDrop">
            <option value="0">---Select Vender Name----</option>
        </select>
        <select class="" id="CompanyDrop">
            <option value="0">---Select Company Name----</option>
            <option value="1">---Select Company 1   ----</option>
            <option value="2">---Select Company 2   ----</option>
            <option value="3">---Select Company 3   ----</option>
            <option value="4">---Select Company 4   ----</option>
            <option value="5">---Select Company 5   ----</option>
            <option value="6">---Select Company 6   ----</option>
            <option value="7">---Select Company 7   ----</option>
            <option value="8">---Select Company 8   ----</option>
            <option value="9">---Select Company 9   ----</option>
        </select>
    
        <br /><br />
    
        <table id="blogTable" class="zui-table zui-table-rounded">
            <thead>
                <tr>
                    <th>Product ID</th>
                    <th>Product Name</th>
                    <th>Purchase Rate</th>
                    <th>Qty</th>
                    <th>Value</th>
                    <th>Checkbox</th>
                </tr>
            </thead>
            <tbody></tbody>
            <tfoot>
                <tr>
                    <td colspan="4" style="text-align:center">Total Value</td>
                    <td colspan="2" style="text-align:center" class="total-sum">0</td>
                </tr>
            </tfoot>
        </table>
    
        <br />
        <input type="submit" value="Submit" />
    </form>
    
    

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards,
    Jason

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Fengzhi Zhou - MSFT 0 Reputation points Microsoft Vendor
    2023-09-12T14:55:21.2033333+00:00

    Hi @jewel,

    Please check the sample code.

    Index.html

    @{
           ViewData["Title"] = "How to Select List";
    }
    <style type="text/css">
           #blogTable {
                  border-collapse: collapse;
                  border: 1px solid black;
           }
                  #blogTable th, #blogTable td {
                         border: 1px solid black;
                         padding: 8px;
                  }
    </style>
    <select class="" id="VenderDrop">
           <option value="0">---Select Vender Name----</option>
           
    </select>
    <select class="" id="CompanyDrop">
           <option value="0">---Select Company Name----</option>
    </select>
    <table id="blogTable" class="zui-table zui-table-rounded">
           <thead>
                  <tr>
                         <th>Product ID</th>
                         <th>Product Name</th>
                         <th>Purchase Rate</th>
                         <th>Qty</th>
                         <th>value</th>
                         <th>Company Name</th>
                         <th>Checkbox</th>
                         <th>Vender ID</th>
                         <th>Vender Name</th>
                         
                  </tr>
           </thead>
           <tbody></tbody>
           <tfoot>
                  <tr>
                         <td></td>
                         <td></td>
                         <td></td>
                         <td></td>
                         <td></td>
                         <td>Total Value :</td>
                         <td></td>
                         <td></td>
                         <td></td>
                  </tr>
           </tfoot>
    </table>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <!-- Including jQuery library -->
    <script>
           $(document).ready(function () {
                  //init vender and company
                        VenderInit();
                         CompanyInit();
                         GetVenderSelectList();
                         GetCompanySelectList();
           $('#VenderDrop').change(function () {
                  GetVenderSelectList();
           });
           $("#CompanyDrop").change(function () {
                  GetCompanySelectList();
           });
    })
    
    function VenderInit() {
           $.ajax({
                  url: '/SelectList/vendername',
                  type: 'Get',
                  datatype: 'json',
                  data: {
                         venderid: $("#VenderDrop").val(),
                         vcompanyid: $("#CompanyDrop").val()
                  },
                  success: function (data) {
                         $.each(data, function (i, item) {
                                $("#VenderDrop").append('<option value=' + item.vender_ID + '>' + item.vender_Name + '</option>');
                         });
                  }
           });
    }
    
    function CompanyInit() {
           $.ajax({
                  url: '/SelectList/GetProductRecord',
                  type: 'Get',
                  datatype: 'json',
                  data: {
                         cvenderid: $("#VenderDrop").val(),
                         companyid: $("#CompanyDrop").val()
                  },
                  success: function (data) {
                         $.each(data, function (i, item) {
                                $("#CompanyDrop").append('<option value=' + item.productID + '>' + item.productName + '</option>');
                         });
                  }
           });
    }
                  
           })
           function GetVenderSelectList() {
                  $.ajax({
                         url: '/SelectList/vendername',
                         type: 'Get',
                         datatype: 'json',
                         data: {
                                venderid: $("#VenderDrop").val()
                         },
                         success: function (data) {
                                $('#blogTable tbody').empty();
                                $.each(data, function (i, item) {
                                       var rows = "<tr>"
                                              + "<td>" + item.productID + "</td>"
                                              + "<td>" + item.productName + "</td>"
                                              + "<td>" + item.purchaseRate + "</td>"
                                              + "<td><input type='number' value='' min='1' onkeypress='return isNumberKey(event)' class='txt_qty' data-rate='" + item.purchaseRate + "'/></td>"
                                              + "<td><label class='total-value'></label></td>"
                                              + "<td>" + '<label ></label>' + "</td>"
                                              + "<td><input type='checkbox' name='Selectone' class='chk_isChecked' id='" + item.productID + "'/></td>"
                                              + "<td>" + item.vender_ID + "</td>"
                                              + "<td>" + item.vender_Name + "</td>"
                                              + "</tr>";
                                       $('#blogTable tbody').append(rows);
                                       $(".txt_qty").on("input", function () {
                                              var rate = $(this).data("rate");
                                              var qty = $(this).val();
                                              var total = rate * qty;
                                              $(this).closest("tr").find(".total-value").text(total);
                                       });
                                });
                         }
                  });
           }
           function GetCompanySelectList() {
                  $.ajax({
                         url: '/SelectList/GetProductRecord',
                         type: 'Get',
                         datatype: 'json',
                         data: {
                                companyid: $("#CompanyDrop").val()
                         },
                         success: function (data) {
                                $('#blogTable tbody').empty();
                                $.each(data, function (i, item) {
                                       var rows = "<tr>"
                                              + "<td>" + item.productID + "</td>"
                                              + "<td>" + item.productName + "</td>"
                                              + "<td>" + item.purchaseRate + "</td>"
                                              + "<td><input type='number' value='' min='1' onkeypress='return isNumberKey(event)' class='txt_qty' data-rate='" + item.purchaseRate + "'/></td>"
                                              + "<td><label class='total-value'></label></td>"
                                              + "<td>" + '<label ></label>' + "</td>"
                                              + "<td>" + '<input type="checkbox" name="Selectone" class="chk_isChecked" id="item.productID" />' + "</td>"
                                              + "<td>" + item.vender_ID + "</td>"
                                              + "<td>" + item.vender_Name + "</td>"
                                              + "</tr>";
                                       $('#blogTable tbody').append(rows);
                                       $(".txt_qty").on("input", function () {
                                              var rate = $(this).data("rate");
                                              var qty = $(this).val();
                                              var total = rate * qty;
                                              $(this).closest("tr").find(".total-value").text(total);
                                
                                       });
                                });
                         }
                  })
           }
           
           $(function () {
                  debugger
                  …
                  Your debugger function
    …
           })
           
    </script>
    

    SelectListController.cs

    using Microsoft.AspNetCore.Mvc;
    using Newtonsoft.Json;
    namespace WebApplication0912.Controllers
    {
        public class SelectListController : Controller
        {
            public IActionResult Index()
            {
                List<tbl_Product> mockData = new List<tbl_Product>();
                for (int i = 1; i <= 10; i++)
                {
                    tbl_Product p = new tbl_Product();
                    p.productID = i;
                    p.productName = "ProductName-" + i;
                    p.purchaseRate = new decimal(i);
                    p.CompanyId = i;
                                  p.ProductCategoryId = i;
                                  p.ProductCategoryCategoryId = i;
                                  mockData.Add(p);
                }
                var prolist = new List<tbl_Product>();
                prolist = mockData.ToList();
                return View(prolist);
            }
                  [HttpGet]
    public IActionResult GetProductRecord(int companyid,int cvenderid)
    {
           List<tbl_Product> mockData = new List<tbl_Product>();
        for (int i = 1; i <= 10; i++)
        {
            tbl_Product p = new tbl_Product();
            p.vender_ID = i;
                  p.productID = i;
            p.productName = "ProductName-" + i;
            p.vender_Name = "VenderName-" + i;
            p.purchaseRate = new decimal(i);
            p.CompanyId = i;
                  p.ProductCategoryId = i;
                  p.ProductCategoryCategoryId = i;
                  mockData.Add(p);
           }
        var List = new List<tbl_Product>();
        if (companyid == 0)
        {
            List = mockData;
        }
           else if(cvenderid == 0)
           {
            List = mockData.Where(a => a.CompanyId == companyid).ToList();
        }
           //multi judge
           else
           {
                  List = mockData.Where(a => a.vender_ID == cvenderid).Where(x => x.CompanyId == companyid).ToList();
           }
           return Json(List);
    }
                 [HttpGet]
    public IActionResult vendername(int venderid,int vcompanyid)
    {
        List<tbl_Vender> mockData = new List<tbl_Vender>();
        for (int i = 1; i <= 10; i++)
        {
            tbl_Vender p = new tbl_Vender
            {
                vender_ID = i,
                vender_Name = "VenderName-" + i,
                         productName = "ProductName-" + i,
                      productID = i,
                purchaseRate = new decimal(i),
                         ProductCategoryId = i,
                      ProductCategoryCategoryId = i,
                CompanyId = i
               };
            mockData.Add(p);
        }
        var venders = new List<tbl_Vender>(); 
           if (venderid == 0)
           {
                  venders = mockData;
           }
           else if (vcompanyid == 0)
           {
                  venders = mockData.Where(a => a.vender_ID == venderid).ToList();
           }
           //multi judge
           else
           {
                  venders = mockData.Where(a => a.CompanyId == vcompanyid).Where(x => x.vender_ID == venderid).ToList();
           }
           return Json(venders);
    }
          
        }
           
    public class tbl_Vender
    {
        public int vender_ID { get; set; } 
        public string? vender_Name { get; set; }
        public int productID { get; set; }
        public string? productName { get; set; }
        public decimal purchaseRate { get; set; }
        public int ProductCategoryId { get; set; }
        public int ProductCategoryCategoryId { get; set; }
        public int CompanyId { get; set; }
    }
    public class tbl_Product
    {
            public int vender_ID { get; set; }
            public string? vender_Name { get; set; }
            public int productID { get; set; }
            public string? productName { get; set; }
            public decimal purchaseRate { get; set; }
            public int ProductCategoryId { get; set; }
            public int ProductCategoryCategoryId { get; set; }
            public int CompanyId { get; set; }  
    }
    }
    

    selectlist


    You can move tbl_Vender and and tbl_ Product to model folder.

    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    Best regards

    Ronaldoz


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.