OrderDetails not populating

Feb 17, 2013 at 10:26 PM
I have been stuck on this issue for a few days now and i dont know what what to do.

I am able to put items into my shopping cart, sign in and the cart name gets updated from the session id to a username, but when i go to do a check out and add the name, address, and the other items required for checkout, it comes right back to the same screen when i click on submit.

When i check the database, i see that the Order table was updated, but the OrderDetails is still blank. Also the shopping cart still has items in it.

While trying to troubleshoot the issue, I did something else to either the controller or the model and i am no longer able to update the Order table :-(. I also noticed that the CreateOrder section of the shoppingcart never gets executed while trying to add items into the Order.. Not sure if thats due to something i did in efforts to correct the issues.. but yeah, any help would be greatly appreciated. I will post up my controllers and models after this gets posted.

Thanks again!
Feb 17, 2013 at 10:27 PM
ShoppingCart Controller
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using OrderCentral.Data;
using OrderCentral.ViewModels;

namespace OrderCentral.Controllers
{
public class ShoppingCartController : Controller 
    { 
        OrderCentralDb _db = new OrderCentralDb(); 
        // 
        // GET: /ShoppingCart/ 
        public ActionResult Index() 
        { 
            var cart = ShoppingCart.GetCart(this.HttpContext); 
  
            // Set up our ViewModel 
            var viewModel = new ShoppingCartViewModel 
            { 
                CartItems = cart.GetCartItems(), 
                CartTotal = cart.GetTotal() 
            }; 
            // Return the view 
            return View(viewModel); 
        } 
        // 
        // GET: /Store/AddToCart/5 
        public ActionResult AddToCart(int id) 
        { 
            // Retrieve the product from the database 
            var addedProduct = _db.Products 
                .Single(products => products.ProductID == id); 
  
            // Add it to the shopping cart 
            var cart = ShoppingCart.GetCart(this.HttpContext); 
  
            cart.AddToCart(addedProduct); 
  
            // Go back to the main store page for more shopping 
            return RedirectToAction("Index"); 
        } 
        // 
        // AJAX: /ShoppingCart/RemoveFromCart/5 
        [HttpPost] 
        public ActionResult RemoveFromCart(int id) 
        { 
            // Remove the item from the cart 
            var cart = ShoppingCart.GetCart(this.HttpContext); 
  
            // Get the name of the product to display confirmation 
            string productName = _db.Carts 
                .Single(item => item.RecordId == id).Product.ProductName; 
  
            // Remove from cart 
            int itemCount = cart.RemoveFromCart(id); 
  
            // Display the confirmation message 
            var results = new ShoppingCartRemoveViewModel 
            {

                Message = "The item " + Server.HtmlEncode(productName) + 
                    " has been removed from your shopping cart.", 
                CartTotal = cart.GetTotal(), 
                CartCount = cart.GetCount(), 
                ItemCount = itemCount, 
                DeleteId = id 
            }; 
            return Json(results); 
        } 
        // 
        // GET: /ShoppingCart/CartSummary 
        [ChildActionOnly] 
        public ActionResult CartSummary() 
        { 
            var cart = ShoppingCart.GetCart(this.HttpContext); 
  
            ViewData["CartCount"] = cart.GetCount(); 
            return PartialView("CartSummary"); 
        } 
    } 
}

Feb 17, 2013 at 10:28 PM
Checkout Controller
using System;
using System.Linq;
using System.Web.Mvc;
using OrderCentral.Models;
using OrderCentral.Data;
using OrderCentral.ViewModels;

namespace OrderCentral.Controllers
{
    [Authorize]
    public class CheckoutController : Controller
    {
        OrderCentralDb storeDB = new OrderCentralDb();
        
        //
        // GET: /Checkout/AddressAndPayment

        public ActionResult AddressAndPayment()
        {
            return View();
        }

        //
        // POST: /Checkout/AddressAndPayment

        [HttpPost]
        public ActionResult AddressAndPayment(FormCollection values)
        {
            var order = new Order();
            TryUpdateModel(order);

            try
            {
                
                    order.Username = User.Identity.Name;
                    order.OrderDate = DateTime.Now;

                    //Save Order
                    storeDB.Orders.Add(order);
                    storeDB.SaveChanges();

                    //Process the order
                    var cart = ShoppingCart.GetCart(this.HttpContext);
                    cart.CreateOrder(order);

                    return RedirectToAction("Complete",
                        new { id = order.OrderId });
                }

            
            catch
            {
                //Invalid - redisplay with errors
                return View(order);
            }
        }

        //
        // GET: /Checkout/Complete

        public ActionResult Complete(int id)
        {
            // Validate customer owns this order
            bool isValid = storeDB.Orders.Any(
                o => o.OrderId == id &&
                o.Username == User.Identity.Name);

            if (isValid)
            {
                return View(id);
            }
            else
            {
                return View("Error");
            }
        }
    }
}
Feb 17, 2013 at 10:29 PM
ShoppingCart Model
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using OrderCentral.Data;
using OrderCentral.ViewModels;
using OrderCentral.Models;

namespace OrderCentral.ViewModels
{
    public partial class ShoppingCart
    {
        OrderCentralDb _db = new OrderCentralDb();
        
        string ShoppingCartId { get; set; }
        
        public const string CartSessionKey = "CartId";
        
        public static ShoppingCart GetCart(HttpContextBase context)
        {
            var cart = new ShoppingCart();
            cart.ShoppingCartId = cart.GetCartId(context);
            return cart;
        }
        
        // Helper method to simplify shopping cart calls 
        public static ShoppingCart GetCart(Controller controller)
        {
            return GetCart(controller.HttpContext);
        }
        
        public void AddToCart(Products products)
        {
            // Get the matching cart and product instances 
            var cartItem = _db.Carts.SingleOrDefault(
                c => c.CartId == ShoppingCartId 
                && c.ProductID == products.ProductID);

            if (cartItem == null)
            {
                // Create a new cart item if no cart item exists 
                cartItem = new Cart
                {
                    ProductID = products.ProductID,
                    CartId = ShoppingCartId,
                    Count = 1,
                    DateCreated = DateTime.Now
                };

                _db.Carts.Add(cartItem);
            }
            else
            {
                // If the item does exist in the cart,  
                // then add one to the quantity 
                cartItem.Count++;
            }
        
            // Save changes 
            _db.SaveChanges();
        }

        public int RemoveFromCart(int id)
        {
            // Get the cart 
            var cartItem = _db.Carts.Single(
                cart => cart.CartId == ShoppingCartId
                && cart.RecordId == id);

            int itemCount = 0;

            if (cartItem != null)
            {
                if (cartItem.Count > 1)
                {
                    cartItem.Count--;
                    itemCount = cartItem.Count;
                }
                else
                {
                    _db.Carts.Remove(cartItem);
                }
                
                // Save changes 
                _db.SaveChanges();
            }
            return itemCount;
        }
        public void EmptyCart()
        {
            var cartItems = _db.Carts.Where(cart => cart.CartId == ShoppingCartId);

            foreach (var cartItem in cartItems)
            {
                _db.Carts.Remove(cartItem);
            }
        
            // Save changes 
            _db.SaveChanges();
        }

        public List<Cart> GetCartItems()
        {
            return _db.Carts.Where(cart => cart.CartId == ShoppingCartId).ToList();
        }
        public int GetCount()
        {
            // Get the count of each item in the cart and sum them up 
            int? count = (from cartItems in _db.Carts
                          where cartItems.CartId == ShoppingCartId
                          select (int?)cartItems.Count).Sum();
            // Return 0 if all entries are null 
            return count ?? 0;
        }
        public decimal GetTotal()
        {
            // Multiply album price by count of that album to get  
            // the current price for each of those albums in the cart 
            // sum all album price totals to get the cart total 
            decimal? total = (from cartItems in _db.Carts
                              where cartItems.CartId == ShoppingCartId
                              select (int?)cartItems.Count * cartItems.Product.ProductPrice).Sum();
            return total ?? decimal.Zero;
        }
     
        public int CreateOrder(Order order)
        {
            decimal orderTotal = 0;

            var cartItems = GetCartItems();
            // Iterate over the items in the cart, adding the order details for each 
            foreach (var item in cartItems)
            {
                var orderDetails = new OrderDetail
                {
                    ProductName = item.ProductID,
                    OrderId = order.OrderId,
                    ProductPrice = item.Product.ProductPrice,
                    Quantity = item.Count
                };
            
                // Set the order total of the shopping cart 
                orderTotal += (item.Count * item.Product.ProductPrice);

                _db.OrderDetails.Add(orderDetails);
                
            }

            // Set the order's total to the orderTotal count 
            order.Total = orderTotal;

            // Save the order 
            _db.SaveChanges();
            
            // Empty the shopping cart 
            EmptyCart();
        
            // Return the OrderId as the confirmation number 
            return order.OrderId;
        }

        // We're using HttpContextBase to allow access to cookies. 
        public string GetCartId(HttpContextBase context)
        {
            if (context.Session[CartSessionKey] == null)
            {
                if (!string.IsNullOrWhiteSpace(context.User.Identity.Name))
                {
                    context.Session[CartSessionKey] = context.User.Identity.Name;
                }
                else
                {
                    // Generate a new random GUID using System.Guid class 
                    Guid tempCartId = Guid.NewGuid();
                    
                    // Send tempCartId back to client as a cookie 
                    context.Session[CartSessionKey] = tempCartId.ToString();
                }
            }
            return context.Session[CartSessionKey].ToString();
        }
        // When a user has logged in, migrate their shopping cart to 
        // be associated with their username 
        public void MigrateCart(string userName)
        {
            var shoppingCart = _db.Carts.Where(c => c.CartId == ShoppingCartId);

            foreach (Cart item in shoppingCart)
            {
                item.CartId = userName;
            }
            _db.SaveChanges();
        }
    }
}
Aug 17, 2013 at 2:59 PM
Hey,

I know it's been a while since you posted this, but I've encountered the same issue as you, and I'm wondering if you ever managed to solve it?