Home > database >  Ability to Add row to ViewModel dynamically with ViewBag
Ability to Add row to ViewModel dynamically with ViewBag

Time:03-08

Background
I'm building a simple Inventory and Ordering System. Where An Order Order.cs have multiple Order Items OrderItem. And I have a ViewModel for it. Also the quantity of Order Items should update the Inventory as well, but I have not gone so far yet

Models

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; }

        [ForeignKey("ItemInfoId")]
        public int ItemInfoId { get; set; }
        
        public int Quantity { get; set; }
        public ItemInfo ItemInfo { get; set; }
        public Order Order { get; set; }
    }
public class OrderViewModel
    {
        //public int OrderId { get; set; }
        //public string OrderNumber { get; set; }
        //public string DeliveryAddress { get; set; }
        //public int ClientId { get; set; }
        //public DateTime Deliverydate { get; set; }
        public Order Order { get; set; }
        public IList<OrderItem> OrderItems { get; set; }
    }

Controller While Create button is been clicked.

public IActionResult Create()
        {
            PopulateClientDropDownList();
            CreateMultipleOrderItem();
            return View();
        }

My CreateMultipleOrderItem() is working and returning me some value.

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();
        }

Razor View

<table id="tblCustomers"  cellpadding="0" cellspacing="0" >
                <h3>Order Items</h3>
                <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].ItemInfoId"  asp-items="@ViewBag.Item"></select>
                        </td>
                        <td><input type="text" asp-for="OrderItems[0].Quantity"  /></td>
                        @*<td><input type="button" id="btnAdd" value="Add" /></td>*@
                    </tr>
                </tfoot>
            </table>
            <button id="add">Add another item</button>
@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    <script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.10.2.js" type="text/javascript"></script>
    <script>
        $("#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" ></select></td>'  
                '<td><input type="text"  name="OrderItems['   i   '].Quantity" /></td>' 
                '<td><button type="button" >Delete</button></td></tr>
'

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

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

           var subItemList = $("#OrderItems"   1   "_ItemInfoId");
            subItemList.empty();
            subItemList.append(Items);
    });
    </script>

}

enter image description here

I'm seeing this now, not sure why when new rows are added, my ViewBag items are not returned to the Select list.

I have been stuck here for few days and this is the closest I have get so far. Really appreciate if someone can help me with this.

CodePudding user response:

var subItemList = $("#OrderItems" 1 "_ItemInfoId");

According to your code: <select id ="OrderItems_' i '_ItemInfoId" name="OrderItems[' i '].ItemInfoId" ></select>

change the id to be consistent with the id in select, like below:

 var subItemList = $("#OrderItems_"   i   "_ItemInfoId");

result:

enter image description here

  • Related