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!