我在控制器方法中设置summaryVm
的值时遇到了一些问题。我接受了OrderVM
并且我已经检查了调试模式,OrderVM
的属性在传递时都已设置,Order
也设置了所有值(包括orderID
})。但是,当我尝试将SummaryVm
的值设置为这些值时,summaryVm.Tickets
为null
的{{1}}就像summaryVm.orderID
一样。然而,email
和eventID
被设置正常。
如果有人对我做错了什么有建议,那就太好了,因为我不知道该怎么回事。
[HttpPost]
public ActionResult Create(OrderVM model)
{
if (!ModelState.IsValid)
return View("CreateOrder", model);
}
string currentUserId = User.Identity.GetUserId();
ApplicationUser currentUser = db.Users.FirstOrDefault(x => x.Id == currentUserId);
Event currentEvent = db.Events.Find(model.EventID);
Order order = new Order
{
OrderDate = DateTime.Now,
EventID = model.EventID,
Event = currentEvent,
user = currentUser
};
float total = 0;
// Initialise a TicketsOrdered data model for each valid ticket
foreach (TicketVm ticket in model.Tickets.Where(t => t.Quantity > 0))
{
total += (ticket.Price*ticket.Quantity);
TicketsOrdered ticketOrder = new TicketsOrdered
{
OrderID = order.OrderID,
TicketID = ticket.TicketID,
Quantity = ticket.Quantity
};
db.ticketsOrdered.Add(ticketOrder);
}
order.OrderTotal = total;
currentEvent.Order.Add(order);
currentUser.Order.Add(order);
SummaryVm summaryVm = new SummaryVm
{
email = order.user.UserName,
orderID = order.OrderID,
tickets = model.Tickets,
totalPrice = total,
eventID=model.EventID,
stripePublishableKey=ConfigurationManager.AppSettings["stripePublishableKey"]
};
db.Orders.Add(order);
db.SaveChanges();
return RedirectToAction("OrderSummary", "Order", summaryVm);
}
public class OrderVM
{
public int ID { get; set; }
public int EventID { get; set; }
public string EventName { get; set; }
// additional properties of Event you want to display
public DateTime OrderDate { get; set; }
public string FirstName { get; set; }
// additional properties of Order and OrderDetails you want to edit
public IList<TicketVm> Tickets { get; set; }
public Event events {get; set;}
}
public class SummaryVm
{
public IList<TicketVm> tickets { get; set; }
public string email { get; set; }
public float totalPrice { get; set; }
public int orderID { get; set; }
public int eventID { get; set; }
public string stripePublishableKey { get; set; }
public string StripeToken { get; set; }
public string StripeEmail {get;set;}
}
答案 0 :(得分:2)
在创建 SummaryVm
之前移动 SaveChanges...
db.Orders.Add(order);
db.SaveChanges();
SummaryVm summaryVm = new SummaryVm
{
email = order.user.UserName,
orderID = order.OrderID,
tickets = model.Tickets,
totalPrice = total,
eventID=model.EventID,
stripePublishableKey=ConfigurationManager.AppSettings["stripePublishableKey"]
};
return RedirectToAction("OrderSummary", "Order", summaryVm);
它会起作用。