How to Insert Array Data

jewel 1,186 Reputation points
2025-06-12T06:12:58.4666667+00:00

I want to create a DotNet Core API application. Where the data has to be added in the form of an array. That is, I want to insert a lot of data at once with one click. But I am not able to get any idea about this. So I am seeking the help of experienced people.

For the convenience of work, I have presented a sample of my work done in .net Core MVC. How can I coordinate this work through API and MVC.

//This is Mvc App jquery Code

function loadData(companyid) {
	$.ajax({
		url: companyid == undefined ? ('/Purchase/GetProductRecord?companyid=-1') : ('/Purchase/GetProductRecord?companyid=' + companyid),
		type: 'Get',
		datatype: 'json',
		success: function (data) {
			$('#my_Lefttbl tbody').empty();
			$.each(data, function (i, item) {
				var rows = "<tr>"
					+ "<td class='productiid' hidden='hidden'>" + item.productID + "</td > "
					+ "<td>" + item.productname + "</td > "
					+ "<td ><label class='purchaserate'>" + item.purchaseRate+ "</label></td>"
					+ "<td ><input  type='number' value='' class='txt_qty' data-rate='" + item.purchaseRate + "'/></td>"
					+ "<td ><label class='total-value tbl_numercvalue'></label></td>"
					+ "</tr>";
				$('#my_Lefttbl tbody').append(rows);
			});
			calculateTotalValue();
		}
	});
}
	function calculateTotalValue() {
		debugger
		$(".txt_qty").off("input").on("input", function () {
				var rate = $(this).data("rate");
		var qty = $(this).val();
		var total = rate * qty;
		var sumtotal = $(this).closest("tr").find(".total-value").text((total === "" ? 0.00 :total.toLocaleString('en-US', { minimumFractionDigits: 2 })));
			var totalValue = 0;
			$("#my_Lefttbl tbody tr").each(function () {
			var value = $(this).closest("tr").find(".total-value").text().replace(/,/g, '');;
			totalValue += (value === "" ? 0.00 : parseFloat(value));
			});
			$(".total-sum").text(totalValue);
		});
	}
		function addata() {
			let valudata = [];
			let txtqty = [];
			let Totalvalue = [];
			
			$("#my_Lefttbl tbody tr").each(function () {
				var qty = $(this).find(".txt_qty").val();
				var id = $(this).find(".productiid").html();
				var totalvalue = $(this).find(".total-value").html();
				if (totalvalue.length > 0 && totalvalue != "0") {
					txtqty.push(qty);
					valudata.push(id);
					Totalvalue.push(totalvalue);
				}
			});
			var objdate = {
				'IDS': valudata,
				'qty': txtqty,
				'totlvau': Totalvalue
				
			};
			$.ajax({
				type: 'POST',
				url: '/Purchase/adddata',
				contentType: 'application/x-www-form-urlencoded; charset=utf-8',
				dataType: "html",
				data: objdate,
				async: false,
				success: function () {
					debugger
					alert("Success")
					window.location.href = "/Purchase/Index";
				},
				Error: function () {
					alert("Error")
				}
			})
			window.location.href = "/Purchase/Index";
		}
//This is Mvc App Controller Code and its work fine
  public IActionResult adddata(int[] IDS, int[] qty,  decimal[] totlvau)
  {
     
      for (int i = 0; i < IDS.Count(); i++)
      {
          var pro = new tbl_purchase();
          pro.productID = IDS[i];
          pro.Qty = qty[i];
          pro.PurchaseValue = totlvau[i];
          _context.tbl_Purchases.Add(pro);
          _context.SaveChanges();
      }
      return RedirectToAction("Index");
  }


//This is My expected api and mvc code without array. i want to this app with array data like upper app

//This is api controller

//public class PurchaseApiController : ControllerBase
[HttpPost("purchaseProduct")]
 public IActionResult adddata(tbl_purchase purchase,[FromQuery] int IDS, [FromQuery] int qty,[FromQuery] decimal totlvau)
 {
         var pro = new tbl_purchase();
         pro.productID = IDS;
         pro.Qty = qty;
         pro.PurchaseValue = totlvau;
         _context.tbl_Purchases.Add(pro);
         _context.SaveChanges();
     return Ok("Success");
 }

//This is mvc controller

//public class PurchaseController : Controller

 public IActionResult adddata(int IDS, int qty,decimal totlvau,tbl_purchase model)
{
        String objdate = "/PurchaseApi/purchaseProduct?qty=" + qty+ "&comid="+comid+ "&idate="+idate+ "&invoiceno="+invoiceno+ "&totlvau="+totlvau+ "&_purchrate="+_purchrate+"&IDS=" + IDS;
    string data = JsonConvert.SerializeObject(model);
    StringContent content = new StringContent(data, Encoding.UTF8, "application/json");
    HttpResponseMessage response = _Client.PostAsync(_Client.BaseAddress + objdate, content).Result;
    if (response.IsSuccessStatusCode)
    {
        TempData["Sucess"]= response.Content.ReadAsStringAsync().Result;
        return RedirectToAction("Index");
    }
    return RedirectToAction("Index");
}
Developer technologies ASP.NET ASP.NET API
{count} votes

Accepted answer
  1. Danny Nguyen (WICLOUD CORPORATION) 165 Reputation points Microsoft External Staff
    2025-06-13T10:10:56.8766667+00:00

    Hello jewel, thanks for reaching out.

    From what I've understood in your expected API, I would suggest creating a DTO (Data Transfer Object) for bulk suggestions using array. You can refer to the implementation here: https://learn.microsoft.com/en-us/aspnet/web-api/overview/data/using-web-api-with-entity-framework/part-5

    When you are sending multiple records from an MVC to a REST api, you should use [FromBody] instead of [FromQuery]

    I have 2 approaches based on your code: Creating a unifed DTO first or Keeeping frontend codes.

    1. Creating a unifed DTO first

    For your case, instead of sending separate arrays you can send a list of objects representing each purchase.

    public class PurchaseDto
    {
        public int ProductID { get; set; }
        public int Qty { get; set; }
        public decimal PurchaseValue { get; set; }
    }
    

    Use [FromBody] to accept the JSON payload:

    [ApiController]
    [Route("api/[controller]")]
    public class PurchaseApiController : ControllerBase
    {
        private readonly YourDbContext _context;
        public PurchaseApiController(YourDbContext context)
        {
            _context = context;
        }
        [HttpPost("purchaseProduct")]
        public IActionResult AddData([FromBody] List<PurchaseDto> purchases)
        {
            foreach (var item in purchases)
            {
                var pro = new tbl_purchase
                {
                    productID = item.ProductID,
                    Qty = item.Qty,
                    PurchaseValue = item.PurchaseValue
                };
                _context.tbl_Purchases.Add(pro);
            }
            _context.SaveChanges();
            return Ok("Bulk insert successful");
        }
    }
    

    JSON payload example:

    [
      { "ProductID": 1, "Qty": 5, "PurchaseValue": 100 },
      { "ProductID": 2, "Qty": 10, "PurchaseValue": 200 }
    ]
    

    You then have to change your appdata() fuction like so to handle the DTO:

    function addata() {
        let purchaseList = [];
        $("#my_Lefttbl tbody tr").each(function () {
            var qty = $(this).find(".txt_qty").val();
            var id = $(this).find(".productiid").html();
            var totalvalue = $(this).find(".total-value").html();
            if (totalvalue.length > 0 && totalvalue != "0") {
                purchaseList.push({
                    ProductID: parseInt(id),
                    Qty: parseInt(qty),
                    PurchaseValue: parseFloat(totalvalue.replace(/,/g, ''))
                });
            }
        });
        $.ajax({
            type: 'POST',
            url: '/Purchase/adddata',
            contentType: 'application/json',
            data: JSON.stringify(purchaseList),
            success: function () {
                alert("Success");
                window.location.href = "/Purchase/Index";
            },
            error: function () {
                alert("Error");
            }
        });
    }
    
    

    2. Keeping frontend implementation

    If you want to keep your frontend addata() function implementations as well as lists for each attributes, you can create a shared DTO class and change the api controller and MVC controller instead

    public class OrderItem
    {
        public int ProductID { get; set; }
        public int Qty { get; set; }
        public decimal TotalValue { get; set; }
    }
    

    Then we can package the lists as List<OrderItem> inside the MVC controller:

    [HttpPost]
    public async Task adddata(int[] IDS, int[] qty, decimal[] totlvau)
    {
        var orderItems = new List();
        for (int i = 0; i < IDS.Length; i++)
        {
            orderItems.Add(new OrderItem
            {
                ProductID = IDS[i],
                Qty = qty[i],
                TotalValue = totlvau[i]
            });
        }
        var jsonData = JsonConvert.SerializeObject(orderItems);
        var content = new StringContent(jsonData, Encoding.UTF8, "application/json");
        var response = await _Client.PostAsync(_Client.BaseAddress + "/api/PurchaseApi/purchaseProduct", content);
        if (response.IsSuccessStatusCode)
        {
            TempData["Success"] = "Data inserted successfully!";
            return RedirectToAction("Index");
        }
        TempData["Error"] = "Failed to insert data.";
        return RedirectToAction("Index");
    }
    

    Now API controller can accept list of OrderItem using [FromBody]

    [HttpPost("purchaseProduct")]
    public IActionResult AddData([FromBody] List<OrderItem> items)
    {
        foreach (var item in items)
        {
            var pro = new tbl_purchase
            {
                productID = item.ProductID,
                Qty = item.Qty,
                PurchaseValue = item.TotalValue
            };
            _context.tbl_Purchases.Add(pro);
        }
        _context.SaveChanges();
        return Ok("Bulk insert successful");
    }
    

    Please let me know which approach you’d prefer: keeping the current frontend implementation using separate lists for attributes, or switching to a unified DTO model. I’ll be happy to assist you further based on your choice!

    2 people found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

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.