Click here to Skip to main content
15,888,351 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am new to programming and trying to save shopping cart and order to database using model binding, the code below is currently saving volunteers to the database but the order details is not saving. The logic of the code is that the user enters registration after checking out without creating an account or password. MVC 5, database first used with repository and a Controller class.

Here is the Code for the Controller and Repository CONTROLLER


What I have tried:

CONTROLLER
public ViewResult Checkout()
   {
       return View(new tbl_Volunteer());
   }

   [HttpPost]
   public ActionResult Checkout([Bind(Include =,VolunDateofbirth," + etc.
   ")] tbl_Volunteer tbl_Volunteer,
        Cart cart, [Bind(Include="OrderLines_ID,Volun_Id,Oppor_Id,
      Quantity,Oppor_Name")] OrderLine orderLine
       )
   {
       if (cart.Lines.Count() == 0)
       {
           ModelState.AddModelError("", "Sorry, your cart is empty!");
       }
       if (ModelState.IsValid)
       {
           tbl_Volunteer.DateCreated = DateTime.Now;
           db.tbl_Volunteer.Add(tbl_Volunteer);
           db.SaveChanges();

           tbl_Volunteer.OrderLines = cart.Lines.ToArray();
          repository.SaveOrder(tbl_Volunteer, cart);
           return RedirectToAction(nameof(Completed));
       }
       else
       {
           return View(tbl_Volunteer);
       }

  REPOSITORY

   private Volunteer_Db objDb;
   private Cart cart;

   public IEnumerable<tbl_Volunteer> Volunteers => db.tbl_Volunteer
   .Include(o => o.OrderLines).Include(l => l.OPPOR_HAS_VOLUN);


   public List<OrderLine> GetBasketLines(tbl_Volunteer volunteer, Cart
   cart)
   {
   return db.OrderLines.Where(b => b.Volun_Id ==
   volunteer.Volun_Id).Include(s => s.tbl_Opportunity).ToList();
   }


   public void SaveOrder(tbl_Volunteer volunteer, Cart cart)
   {
       int orderTotal = 0;

       var basketLines = GetBasketLines(volunteer, cart);
       foreach (var item in basketLines)
       {
           OrderLine orderLine = new OrderLine
           {
               tbl_Opportunity = item.tbl_Opportunity,
               Oppor_Id = item.Oppor_Id,
               Oppor_Name = item.tbl_Opportunity.Oppor_Name,
               Quantity = item.Quantity,
               Volun_Id = volunteer.Volun_Id
           };
           orderTotal += (item.Quantity);
           db.OrderLines.Add(orderLine);
       }
       db.SaveChanges();

   }
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900