How to work with multiple Array Data Asp.net Core

jewel 1,186 Reputation points
2023-08-28T10:11:03.5033333+00:00

I want to save two array data databases in my project. The task is being done correctly but the problem is that the data is being saved multiple times.

PurchaseID       ProductID          Qty

170  1002          10

171  1002          20

172  1002          30

173  1004          10

174  1004          20

175  1004          30

176  1005          10

177  1005          20

178  1005          30

If any experienced would help me. I would benefit. thanks in advance

 public IActionResult adddata(int[] IDS , int[] qty)
        {
            foreach (var id in IDS)
            {
                foreach (var item in qty)
                {
                    var pro = new tbl_purchase();
                    pro.ProductID = id;
                    pro.Qty = item;
                    _context.tbl_Purchases.Add(pro);
                    _context.SaveChanges();
                }      
            }
            return View();
        }
//index.cshtml

 function addata() 
{let valudata=[]         
let txtqty = []         
$('input[name="Selectone"]:checked').each(function (i,data) 
{valudata.push(this.id)});         
$(".txt_qty").each(function (i, tm) 
{var txtvalue = $(tm).val();             
if (txtvalue.length > 0 && txtvalue != "0") 
{txtqty.push(txtvalue)}        
});         
var objdate={             
'IDS': valudata,             
'qty': txtqty         
};        
$.ajax({            
type:'post',            
url:'/PurchaseNew/adddata',            
data:objdate,            
success:function(){                
alert("Ok")            
}        
})      
}
Developer technologies ASP.NET ASP.NET Core
{count} votes

Accepted answer
  1. AgaveJoe 30,126 Reputation points
    2023-08-28T12:13:17.87+00:00

    The code is functioning exactly as written. The code saves every item in the qty array on every iteration of the IDS loop. I assume there should be a relationship between the IDS and qty objects. Unfortunately, we cannot provide any assistance as we have no idea how the code is supposed to work and we cannot see the table schema.

    If the array index relates the two integer arrays then the following should work. But I would rethink the design using a complex type that have the ID and the Quantity rather than two separate int arrays.

    for (int i = 0; i < IDS.Count(); i++)
    {
        var pro = new tbl_purchase();
        pro.ProductID = IDS[i];
        pro.Qty = qty[i];
        _context.tbl_Purchases.Add(pro);
        _context.SaveChanges();    
    }
    
    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.