List is not binding in controller, when pass it through hidden field from view in ASP.NET MVC

44 views Asked by At

This is the payload format of a property showing in the network tab. but in the controller, the below property gets 0, I have provided the razor code as well. PatientPrescriptionOTCModelList: [ { "ProductId": 0, "DrugManufacture": "", "ProductName": "Advil", "Cost": 12, "PatientPay": 0, "ID": "", "Checked": true, "Quantity": 0, "DispenseQuantity": 0, "ProductDescription": "" } ]

[HttpPost]
public IActionResult CheckOut(PatientPrescriptionRootModel 
Model)
{
    HttpContext.Session.SetObjectAsJson("DrugDetails", Model);
    ModelState.Clear();
    ViewBag.data = "CheckOut";
    return View(Model);
 }

 public class PatientPrescriptionRootModel
 { 
     public int ?ID{ get; set; }
     public List<PatientOtcModel>? PatientPrescriptionOTCModelList { get; set; }  
 }

 public class PatientOtcModel
 {
     public int ProductId { get; set; }
     public string DrugManufacture { get; set; }
     public string ProductName { get; set; }
     public double Cost { get; set; }
     public double PatientPay { get; set; }
     public string ID { get; set; }
     public bool Checked { get; set; }
     public double Quantity { get; set; }
     public double DispenseQuantity { get; set; }
     public string ProductDescription { get; set; }
}


 @model ThomosMason.Web.Models.PatientPrescriptionRootModel
 @{

  } 
 @using (Html.BeginForm("CheckOut", "Patient", FormMethod.Post))
 {
   <!DOCTYPE html>
  <html lang="en">
  <head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial- 
   scale=1.0">
  <title>Document</title>
  <!-- bootstrap link -->
  <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
  <!-- font-style link -->
  <link rel="preconnect" href="https://fonts.gstatic.com" 
  crossorigin>
  <link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@300&display=swap" rel="stylesheet">
  <!-- icon-link -->
  <!-- <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> -->
  <!-- google icon-link -->
  <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,GRAD@48,400,0,0" />
  <link rel="stylesheet" href="~/css/PatientPrescription.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
  <link href="~/lib/toast/jquery.toast.min.css" rel="stylesheet" />
  <script src="~/lib/toast/jquery.toast.min.js"></script>
  <script type="text/javascript">
     $(document).ready(function () {
     
          $("#btncheck").click(function (e) {
             if ($(".form-check-input:checked").length == 0) {
                 $.toast({
                     heading: 'Error',
                     text: 'Please Select Value From List',
                     showHideTransition: 'slide',
                     icon: 'error'
                 });
                 return false;
            }
             
          });
        
         $('.form-check-input-all').change(function () {
             debugger;
             var total = 0;
             var i = 0;
             if ($(this).prop('checked') == true) {
                 $(".Checked").val(true);
                 $(".form-check-input").prop('checked', true);
                 $('.form-check-input:checked').each(function () { // iterate through each checked element.
                     total += isNaN(parseFloat($(this).val())) ? 0 : parseFloat($(this).val());
                     i += 1;
                 });
             }
             else {
                 $(".Checked").val(false);
                 $(".form-check-input").prop('checked', false);
                 $('.form-check-input:checked').each(function () { // iterate through each checked element.
                     total += isNaN(parseFloat($(this).val())) ? 0 : parseFloat($(this).val());
                     i += 1;
                 });
             }
             $("#TotalCost").val(total);
            
             $("#PayCost").val(total);
             $("#OTY").html(i);
         });
     
         $('.form-check-input').change(function () {
             var closestchecked = $(this).closest('tr').find(".Checked");
             var total = 0;
             var i = 0;
             if ($(this).prop('checked') == true) {
                 closestchecked.val(true);
             } else {
                 closestchecked.val(false);
             }
             $('.form-check-input:checked').each(function () { // iterate through each checked element.
                 total += isNaN(parseFloat($(this).val())) ? 0 : parseFloat($(this).val());
                 i += 1;
             });
             $("#TotalCost").val(total);
            
             $("#PayCost").val(total);
             $("#OTY").html(i);
             if ($(this).is(":checked")) {
                 
                 var drugName = $(this).closest('tr').find('.drug').val().split(' ')[0];
     
                 // Make an AJAX request to your API endpoint
                 $.ajax({
                     url: 'http://localhost:5179/api/otcproduct/suggestedotclist',
                     type: 'POST', // or 'GET' depending on your API
                     contentType: 'application/json', // Set the content type explicitly
                     data: JSON.stringify({
                         Drugname: drugName
                     }), // Stringify your data if sending JSON
                     success: function (response) {
                         // Handle the API response and add data to the table below
                         if (response.data.length > 0) {
                             // If there is data in the response, append it to the table
                             $.each(response.data, function (index, item) {
                                 var price = item.price ? item.price : 0; // If item.price is null or '', set it to 0
                                 var stockStatus = item.stockStatus ? item.stockStatus : 'NA'; // If item.stockStatus is null or '', set it to 'NA'
                                 var newRow = "<tr><td><input type='checkbox' class='form-check-input-otc'></td><td>" + item.productName + "</td><td><input type='text' class='form-control quantity' value='1'></td><td>" + price + "</td><td>" + stockStatus + "</td></tr>";
                                 $("#example tbody").append(newRow);
                             });
                             // Reinitialize DataTable
                             $("#example").DataTable();
                         }
                     },
                     error: function (xhr, status, error) {
                         // Handle errors if any
                         console.error(xhr.responseText);
                     }
                 });
             } else {
                 // Remove the corresponding row from the table below if the checkbox is unchecked
                 var drugName = $(this).closest('tr').find('.drug').val();;
                 console.log("Drug Name:", drugName); // Log drugName to see its value
                 $("#example tbody tr").each(function () {
                     var cellContent = $(this).find("td:eq(1)").text();
                     console.log("Cell Content:", cellContent);
                     if ($(this).find("td:eq(1)").text().indexOf(drugName) !== -1) {
                         $(this).remove();
                     }
                 });
                        
                 // Reinitialize DataTable
                 $("#example").DataTable();
             }
             // Check if DataTable is empty and hide the message
             var table = $("#example").DataTable();
             if (table.data().count() === 0) {
                 $(".dataTables_empty").hide();
             }
         });
     
         $(document).on('change', '.form-check-input-otc', function () {
             // Retrieve the existing total cost value or set it to 0 if it's not present
             var existingTotal =  0;
             var currentotal = 0;
     
             // Calculate the total cost by adding the existing total to the price of checked items
             var total = existingTotal;
             $('.form-check-input:checked').each(function () {
                 var drugRow = $(this).closest('tr'); // Find the closest row
                 var price = parseFloat(drugRow.find('td:nth-child(6)').text().replace('$', '')) || 0; // Get the price from the sixth column
                 existingTotal += isNaN(price) ? 0 : price; // Add the price to the total
             });
     
             // Iterate through each checked element and calculate the total cost
             $('.form-check-input-otc:checked').each(function () {
                 // Find the closest row in the tbldruglist table and retrieve the price from the sixth column (index 5)
                 var price = parseFloat($(this).closest('tr').find('td:nth-child(4)').text().replace('$', '')) || 0;
                 currentotal += isNaN(price) ? 0 : price; // Add the price to the total
             });
             
             // Update the total cost in the textbox
             $("#TotalCost").val(existingTotal + currentotal);
            
             $("#PayCost").val(existingTotal + currentotal);
             
             $("#OTY").html($('.form-check-input-otc:checked').length); // Update the quantity of checked checkboxes
     
             //assigned selected otc to hidden fileds
             var patientPrescriptionOTCModelList = []; // Initialize an empty array to store PatientOtcModel objects
             // Iterate through each checked row in the #example table
             $('.form-check-input-otc:checked').each(function () {
                 var productName = $(this).closest('tr').find('td:nth-child(2)').text(); // Retrieve product name from the second column (index 1)
                 var price = parseFloat($(this).closest('tr').find('td:nth-child(4)').text().replace('$', '')) || 0; // Retrieve price from the fourth column (index 3)
     
                 // Construct a PatientOtcModel object with the retrieved data
                 var patientOtcModel = {
                     ProductId: 0, // Assign appropriate value if needed
                     DrugManufacture: "", // Assign appropriate value if needed
                     ProductName: productName,
                     Cost: price,
                     PatientPay: 0, // Assign appropriate value if needed
                     ID: "", // Assign appropriate value if needed
                     Checked: true, // Set to true as it is checked
                     Quantity: 0, // Assign appropriate value if needed
                     DispenseQuantity: 0, // Assign appropriate value if needed
                     ProductDescription: "" // Assign appropriate value if needed
                 };
     
                 // Push the PatientOtcModel object to the array
                 patientPrescriptionOTCModelList.push(patientOtcModel);
             });
             // Assign the constructed array to the PatientPrescriptionOTCModelList in the hidden field
             $('#PatientPrescriptionOTCModelList').val(JSON.stringify(patientPrescriptionOTCModelList));
             console.log(patientPrescriptionOTCModelList);
             
            
         });
     
         $(document).on('input', '.form-control.quantity', function () {
             // Get the closest row
             var row = $(this).closest('tr');
     
             // Get the price and quantity from the row
             var price = parseFloat(row.find('td:nth-child(4)').text());
             var quantity = parseInt($(this).val());
     
             // Check if quantity is valid
             if (!isNaN(quantity) && quantity !== 0 && quantity !== null && quantity !== '' && quantity !== undefined) {
                 // Calculate the subtotal for this row
                 var subtotal = price * quantity;
     
                 // Update the subtotal column in this row
                // row.find('td:nth-child(5)').text(subtotal);
             } else {
                 // If quantity is invalid, set subtotal to 0
                // row.find('td:nth-child(5)').text(0);
             }
     
             // Recalculate the total cost
             var total = 0;
             var existingTotal = 0;
             var currentotal = 0;
     
             // Calculate the total cost by adding the existing total to the price of checked items                   
             $('.form-check-input:checked').each(function () {
                 var drugRow = $(this).closest('tr'); // Find the closest row
                 var price = parseFloat(drugRow.find('td:nth-child(6)').text().replace('$', '')) || 0; // Get the price from the sixth column
                 existingTotal += isNaN(price) ? 0 : price; // Add the price to the total
             });
             // Calculate subtotal only if it's valid
             var subtotal = !isNaN(quantity) && quantity !== 0 && quantity !== null && quantity !== '' && quantity !== undefined ? price * quantity : 0;
     
             // Round the total to two decimal places
             var roundedTotal = (existingTotal + subtotal).toFixed(2);
             // Update the total cost fields
             $("#TotalCost").val(roundedTotal);
             
             $("#PayCost").val(roundedTotal);
             $("#OTY").html($('.form-check-input:checked').length);
         });
     
     
     });
     
     
     
  </script>
  <script>
     //javascript for paidorder
     $(document).ready(function () {
         $("#tableotcorder").DataTable({
             "processing": true,
             "serverSide": true,
             "filter": true,
     
             "ajax": {
                 "url": '@Url.Action("OtcOrderList","OTCOrder")',
                 "type": "POST",
                 "datatype": "json"
             },
             "columns": [
     
                 { "data": "productName", "name": "productName", "autoWidth": true },
                 { "data": "orderDate", "name": "orderDate", "autoWidth": true },
                 { "data": "paidAmount", render: $.fn.dataTable.render.number(',', '.', 2, '$') },
                 { "data": "amount", render: $.fn.dataTable.render.number(',', '.', 2, '$') },
                 { "data": "orderStatus", "name": "orderStatus", "autoWidth": true },
                 { "data": "orderId", "name": "orderId", "autoWidth": true },
                 { "data": "trackingId", "name": "trackingId", "autoWidth": true },
                 {
                     data: null,
                     render: function (data, type, row) {
                         return `<button type='button' class='btn btn-view' id='btnViewOrder' data-orderid="` + data.orderId + `"/>view</button>`;
     
                     }
                 }
     
             ],
             'columnDefs': [{
                 'targets': [0, 5, 6], // column index (start from 0)
                 'orderable': false, // set orderable false for selected columns
             }]
         });
     
         $('#tableotcorder tbody').on('click', '#btnViewOrder', function (e) {
             e.preventDefault();
             var UserId = $(this).attr('data-orderid');
             let userName = "Provider";
             location.href = '@Url.Action("OTCOrderDetail", "OTCOrder")?OrderId=' + UserId;
         })
     });
     
  </script>
  <script>
     $(document).ready(function () {
     
     $("#tblorder").DataTable({
         "processing": true,
         "serverSide": true,
         "filter": true,
     
         "ajax": {
             "url": '@Url.Action("OrderList","Order")',
             "type": "POST",
             "datatype": "json"
         },
         "columns": [
     
             { "data": "productName", "name": "productName", "autoWidth": true },
             { "data": "orderDate", "name": "orderDate", "autoWidth": true },
             { "data": "paidAmount", render: $.fn.dataTable.render.number(',', '.', 2, '$') },
             { "data": "transactionId", "name": "transactionId", "autoWidth": true },
             { "data": "orderId", "name": "orderId", "autoWidth": true },
             { "data": "trackingId", "name": "trackingId", "autoWidth": true },
             {
                 data: null,
                 render: function (data, type, row) {
                     return `<button type='button' class='btn btn-view' id='btnViewOrder' data-orderid="` + data.orderId + `"/>view</button>`;
     
                 }
             }
     
         ],
         'columnDefs': [{
             'targets': [0, 5, 6], // column index (start from 0)
             'orderable': false, // set orderable false for selected columns
         }]
     });
     
     $('#tblorder tbody').on('click', '#btnViewOrder', function (e) {
         e.preventDefault();
         var UserId = $(this).attr('data-orderid');
         let userName = "Provider";
         location.href = '@Url.Action("OrderDetails", "Order")?OrderId=' + UserId;
     })
     
     });
     
  </script>
  <script>
     $(document).ready(function () {
         $("#pendingorderstab").click(function () {
            
             $("#pendingtab").show();
             $("#paidtab").hide();
         });
         $("#paidorderstab").click(function () {
             $("#paidtab").show();
             $("#pendingtab").hide();
         });
        
     });
  </script>
     </head>
     <body>
     <div class="header-section-wrapper">
     <div class="container">
        <div class="header-section">
           <div class="logo-section">
              <img src="~/assets/Logo-White.svg" alt="">
           </div>
           <div class="user-detail-wrapper d-flex justify-content-center align-items-center">
              <div class="user-detail me-2">
                 <p class="mb-0">JW</p>
              </div>
              <div class="user-information">
                 <p class="mb-0 text-white">Patient</p>
                 <h6 class="text-white">@Model.Name</h6>
              </div>
           </div>
        </div>
     </div>
  </div>
  <nav>
     <div class="nav nav-tabs mb-3 mt-5 border-0"  id="nav-tab" role="tablist">
     @*<button class="nav-link active" id="nav-home-tab" data-bs-toggle="tab" data-bs-target="#nav-home" type="button" role="tab" aria-controls="nav-home" aria-selected="true">Prescription List</button>*@
     @* 
     <div class="card p-3 mb-3">
        *@
        <div class="container-fluid px-4">
           <div class="tab-wrapper">
              <ul class="nav nav-tabs border-0" data-bs-tabs="tabs" style="left: 10rem">
                 <li class="nav-item">
                    <a class="nav-link active" aria-current="true" data-bs-toggle="tab" href="#step1" id="pendingorderstab">
                    Pending Orders
                    </a>
                 </li>
                 <li class="nav-item">
                    <a class="nav-link" data-bs-toggle="tab" href="#step2" id="paidorderstab">Paid Orders</a>
                 </li>
              </ul>
           </div>
        </div>
     </div>
  </nav>
  <div class="container" id="pendingtab">
     <div class="tab-content p-3 border bg-light" id="nav-tabContent">
        <div class="tab-pane fade active show" id="nav-home" role="tabpanel" aria-labelledby="nav-home-tab">
           <div class="prescription-wrapper">
              <div class="table-responsive">
                 <table class="table table-striped table-bordered" id="tbldruglist">
                    <tr>
                       <th><input type="checkbox" class="form-check-input-all"></th>
                       <th>Script#</th>
                       <th>Drug</th>
                       <th>Quantity</th>
                       <th>Plan</th>
                       <th>Cost</th>
                    </tr>
                    @if (Model.PatientPrescriptionModelList != null)
                    {
                    @for (int i = 0; i <= Model.PatientPrescriptionModelList.Count - 1; i++)
                    {
                    <tr>
                       <td>
                          <input type="checkbox" class="form-check-input" value="@Model.PatientPrescriptionModelList[i].Cost">
                          @Html.HiddenFor(c=>Model.PatientPrescriptionModelList[i].Checked,new{ @Class="Checked"})  
                          @Html.HiddenFor(c=>Model.PatientPrescriptionModelList[i].DrugName,new{ @Class="drug"})  
                          @Html.HiddenFor(c=>Model.PatientPrescriptionModelList[i].Cost,new{ @Class="cost"}) 
                          @Html.HiddenFor(c=>Model.PatientPrescriptionModelList[i].Quantity,new{ @Class="Quantity"})
                          @Html.HiddenFor(c=>Model.PatientPrescriptionModelList[i].ProductDescription,new{ @Class="ProductDescription"})
                          @Html.HiddenFor(c=>Model.PatientPrescriptionModelList[i].ScriptNumber,new{ @Class="ScriptNumber"})
                       </td>
                       <td>@Model.PatientPrescriptionModelList[i].ScriptNumber</td>
                       <td>@Model.PatientPrescriptionModelList[i].DrugName</td>
                       <td>@Model.PatientPrescriptionModelList[i].Quantity</td>
                       <td>@Model.PatientPrescriptionModelList[i].NDC</td>
                       <td>$ @Model.PatientPrescriptionModelList[i].Cost</td>
                    </tr>
                    }
                    }
                 </table>
              </div>
           </div>
           <nav class="navbar navbar-expand-lg navbar-light bg-transparent pt-4 px-4">
              <div class="d-flex align-items-center">
                 <i class="fas fa-align-left primary-text fs-4 me-3" id="menu-toggle"></i>
                 <h2 class="fs-4 m-0">Suggested OTC Products</h2>
              </div>
           </nav>
           <div class="master-tab-wrapper patient-list-wrapper">
              <div class="container-fluid px-4">
                 <div class="row">
                    <div class="col-md-12">
                       <div class="table-responsive">
                          <table id="example" class="table" style="width:100%;">
                             <thead>
                                <tr>
                                   <th><input type="checkbox" class="form-check-input-all-otc"></th>
                                   <th>Product Name</th>
                                   <th>Quantity</th>
                                   <th>Price/Unit</th>
                                   <th>Stock Status</th>
                                </tr>
                             </thead>
                             <tbody>
                             </tbody>
                          </table>
                       </div>
                    </div>
                 </div>
              </div>
           </div>
           <div class="prescription-detail-wrapper">
              <div class="details-wrapper">
                 <div>
                    @* <span>Qty :</span>
                    <span id="OTY">0</span>*@
                 </div>
                 <div class="d-flex align-items-center">
                    <label for="" class="me-3">Total : $</label>
                    <input type="text" class="form-control" id="TotalCost">
                    @Html.HiddenFor(c=>c.TotalCost,new{id="PayCost"})
                    @Html.HiddenFor(c=>c.PatientID,new{id="PatientID"})
                    @Html.HiddenFor(c=>c.PatientPrescriptionOTCModelList,new{id="PatientPrescriptionOTCModelList"})
                 </div>
              </div>
           </div>
        </div>
     </div>
     <div class="checkout-btn float-end mt-5 ">
        <input class="btn d-flex justify-content-center align-items-center" id="btncheck" type="submit" value="CheckOut" />
     </div>
  </div>
  <div class="container" id="paidtab"   style="display:none">
     <div class="master-tab-wrapper patient-list-wrapper">
        <div class="container-fluid px-4">
           <div class="row">
              <div class="col-md-12">
                 <table id="tblorder" class="table" style="width:100%;">
                    <thead>
                       <tr>
                          <th>Product Name</th>
                          <th>Order Date & Time</th>
                          <th>Paid Amount</th>
                          <th>Transaction ID</th>
                          <th>Order ID</th>
                          <th>Tracking ID</th>
                          <th>Actions</th>
                       </tr>
                    </thead>
                    <tbody>
                    </tbody>
                 </table>
              </div>
              </div>
              </div>
              </div>
              </div>
              </body>
              </html>
               }

When the debugger hits the Checkout action method, the property PatientPrescriptionOTCModelList shows a count of 0

0

There are 0 answers