[SOLVED] Missing ViewBag data in jQuery add row

Issue

Heres My Model and ViewModel. I have multiple Models, just showing parts of them for now.

public class Order
    {
        [Key]
        public int Id { get; set; }

        public int TotalItems { get; set; }

        public DateTime DeliveryDate { get; set; }

        public string OrderNumber { get; set; }
        public string DeliveryAddress { get; set; }

        [ForeignKey("ClientId")]
        public int ClientId { get; set; }
        

        public int OrderItemId { get; set; }
        [ForeignKey("OrderItemId")]
        public List<OrderItem> OrderItems { get; set; }
        public Client Client { get; set; }
    }  

public class OrderItem
    {
        public int Id { get; set; }

        [ForeignKey("OrderId")]
        public int OrderId{ get; set; }

        public int InventoryInfoId { get; set; }
        [ForeignKey("InventoryInfoId")]

        [Required]
        public string ItemCode { get; set; }

        public int Quantity { get; set; }
        public virtual InventoryInfo InventoryInfo { get; set; }
        public Order Order { get; set; }
    }   
public class OrderViewModel
    {
        public Order Order { get; set; }
        public List<OrderItem> OrderItems { get; set; }
    }

Basically I want to an Order which can hold a list of OrderItem.
Below is my OrderController. I think there are problems with my Create action here. But I’m not sure how to fix it.

 public IActionResult Create()
        {
            PopulateClientDropDownList();
            CreateMultipleOrderItem();
            return View();
        }
        public IActionResult CreateMultipleOrderItem()
        {
            ViewBag.Item = new SelectList(_context.ItemInfos.ToList(), "Id", "ItemCode");
            ViewBag.Items = JsonConvert.SerializeObject(new SelectList(_context.ItemInfos.ToList(), "Id", "ItemCode"));
            return View();
        }
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create(OrderViewModel OrderVM)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    
                    _context.Add(OrderVM.Order);
                    _context.Add(OrderVM.OrderItems);
                    await _context.SaveChangesAsync();
                    return RedirectToAction(nameof(Index));
                }
            }
            catch (DbUpdateException ex)
            {
                //Log the error(uncomment ex variable name and write a log.
                ModelState.AddModelError("", "Unable to save changes. " +
                    "Try again, and if the problem persists " +
                    "see your system administrator.");
            }
            PopulateClientDropDownList(OrderVM.Order.ClientId);
            CreateMultipleOrderItem();
            return View(OrderVM);
        }

And this is my Order/Create.cshtml

 <table id="tblCustomers" class="table" cellpadding="0" cellspacing="0">
                <thead>
                    <tr>
                        <th style="width:150px">Item Code</th>
                        <th style="width:150px">Quantity</th>
                        <th></th>
                    </tr>
                </thead>
                <tbody></tbody>
                <tfoot id="item-list">
                    <tr>
                        <td>
                            <select asp-for="OrderItems[0].ItemCode" class="items" asp-items="ViewBag.Item"></select>
                        </td>
                        <td><input type="text" asp-for="OrderItems[0].Quantity" class="items" /></td>

                       
                    </tr>
                </tfoot>
            </table>
            <button id="add">Add another item</button>`enter code here`
Scripts {
    <script>
        $("#add").click(function (e) {
           e.preventDefault();
           var i = ($(".items").length) / 3;
           var model = @Html.Raw(@ViewBag.Items);
            var n = '<tr><td><select id="OrderItems_' + i + '_ItemCode" name="OrderItems[' + i + '].ItemCode" class="items" /></td>' +
            '<td><input type="text" class="items" name="OrderItems[' + i + '].Quantity" /></td></tr>' 

           $("#item-list").append(n);

           var Items = "";
           $(model).each(function () {
               Items = Items + '<option value="' + this.Value + '">' + this.Text + '</option>'
           });

           var subItemList = $("#OrderItems" + i + "_ItemCode");
            subItemList.empty();
            subItemList.append(Items);
                });
    </script>
}

I’m seeing this after clicking the add row button.
enter image description here

Guys Please Help!!!

Solution

I have finally solved this problem after 3 days, here’s the solution

$("#add").off("Create");
    $("#add").click(function (e) {
           e.preventDefault();
           var i = ($(".items").length) / 2;
           var model = @Html.Raw(@ViewBag.Items);
            var n = '<tr><td><select id="OrderItems_' + i + '_ItemInfoId" name="OrderItems[' + i + '].ItemInfoId" class="items" /></td>' +
                '<td><input type="text" class="items" name="OrderItems[' + i + '].Quantity" /></td></tr>'

            $("#item-list").append(n);    

        var Items = "";
        ****f = 0;****
        $(model).each(function () {
            Items = Items + '<option value="' + model[f].Value + '">' + model[f].Text + '</option>'
            ****f++;****//previously, the text and value wasn't iterating through the loop, now with index its able to iterate through.
        });
        

            var subItemList = $("#OrderItems_" + i + "_ItemInfoId");
            subItemList.empty();
            subItemList.append(Items);
            });

Answered By – Bruce

Answer Checked By – Clifford M. (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *