I have created a view with multiple models (via ViewModel) to display data from multiple tables (i.e. billing address, shipping address, line items of an order). In my example, I would like to click the submit button to basically place an order, where only part of the information needs to be passed on and stored into a new table (orders), where let's say the billing address ID is referenced to keep it simple.
In a second step I will try to fetch the ID of the new row created in the orders table to update another (line item table). However, for some reason I don't even get beyond creating the record in the orders table - hence help is appreciated!
Below my controller - everything until ModelState validation works, after it breaks and gives me an 'object reference not set to an instance of an object' error...
// POST: /Shop/CreateOrder
[Authorize]
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult SubmitOrder(CreateOrderViewModel model)
{
// define variables
var userID = User.Identity.GetUserId();
DateTime nowUTC = DateTime.Now.ToUniversalTime();
DateTime nowLocal = DateTime.Now.ToLocalTime();
int NumberOfLineItems = DATADB.LineItemList.Where(x => x.OrderNumber == 0 && x.UserID == userID).Count();
decimal OrderAmount = DATADB.LineItemList.Where(x => x.OrderNumber == 0 && x.UserID == userID).Sum(x => x.TotalPrice);
if (ModelState.IsValid)
{
var order = new Orders
{
UserID = userID,
ShippingAddressID = model.ShippingAddressModel.ID,
NumberOfLineItems = NumberOfLineItems,
OrderAmount = OrderAmount,
PaymentMethodID = model.PaymentMethodModel.ID,
OrderDate = nowUTC,
OrderLatitude = model.OrdersModel.OrderLatitude,
OrderLongitude = model.OrdersModel.OrderLongitude,
OrderLocation = model.OrdersModel.OrderLocation
};
DATADB.OrderList.Add(order);
DATADB.SaveChanges();
int orderID = order.ID;
var lineItems = DATADB.LineItemList.Where(x => x.OrderNumber == 0 && x.UserID == userID);
lineItems.ForEach(l => l.OrderNumber = orderID);
DATADB.SaveChanges();
return View("Home", "Home");
}
else
{
return View(model);
}
}
The view model looks as follows:
public class CreateOrderViewModel
{
public Orders OrdersModel { get; set; }
public LineItems LineItemModel { get; set; }
public IEnumerable<LineItems> LineItemListModel { get; set; }
public ShippingAddressesViewModel ShippingAddressModel { get; set; }
public ProfileInformationViewModel ProfileInformationModel { get; set; }
public PaymentMethods PaymentMethodModel { get; set; }
}
... and the orders model like this:
public class Orders
{
public int ID { get; set; }
public string UserID { get; set; }
public int ShippingAddressID { get; set; }
public int NumberOfLineItems { get; set; }
public int PaymentMethodID { get; set; }
public decimal OrderAmount { get; set; }
public decimal ShippingCost { get; set; }
public DateTime OrderDate { get; set; }
public string OrderLatitude { get; set; }
public string OrderLongitude { get; set; }
public string OrderLocation { get; set; }
}