/MvcMusicStore/Controllers/CheckoutController.cs

# · C# · 83 lines · 60 code · 13 blank · 10 comment · 5 complexity · dfc295a35fae1c258a1766b6e001160a MD5 · raw file

  1. using System;
  2. using System.Linq;
  3. using System.Web.Mvc;
  4. using MvcMusicStore.Models;
  5. namespace MvcMusicStore.Controllers
  6. {
  7. [Authorize]
  8. public class CheckoutController : Controller
  9. {
  10. MusicStoreEntities storeDB = new MusicStoreEntities();
  11. const string PromoCode = "FREE";
  12. //
  13. // GET: /Checkout/AddressAndPayment
  14. public ActionResult AddressAndPayment()
  15. {
  16. return View();
  17. }
  18. //
  19. // POST: /Checkout/AddressAndPayment
  20. [HttpPost]
  21. public ActionResult AddressAndPayment(FormCollection values)
  22. {
  23. var order = new Order();
  24. TryUpdateModel(order);
  25. try
  26. {
  27. if (string.Equals(values["PromoCode"], PromoCode,
  28. StringComparison.OrdinalIgnoreCase) == false)
  29. {
  30. return View(order);
  31. }
  32. else
  33. {
  34. order.Username = User.Identity.Name;
  35. order.OrderDate = DateTime.Now;
  36. //Save Order
  37. storeDB.Orders.Add(order);
  38. storeDB.SaveChanges();
  39. //Process the order
  40. var cart = ShoppingCart.GetCart(this.HttpContext);
  41. cart.CreateOrder(order);
  42. return RedirectToAction("Complete",
  43. new { id = order.OrderId });
  44. }
  45. }
  46. catch
  47. {
  48. //Invalid - redisplay with errors
  49. return View(order);
  50. }
  51. }
  52. //
  53. // GET: /Checkout/Complete
  54. public ActionResult Complete(int id)
  55. {
  56. // Validate customer owns this order
  57. bool isValid = storeDB.Orders.Any(
  58. o => o.OrderId == id &&
  59. o.Username == User.Identity.Name);
  60. if (isValid)
  61. {
  62. return View(id);
  63. }
  64. else
  65. {
  66. return View("Error");
  67. }
  68. }
  69. }
  70. }