ProductController.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. using Microsoft.AspNetCore.Diagnostics;
  2. using Microsoft.AspNetCore.Mvc;
  3. using Products.Backoffice.Models;
  4. using Products.Business.Service;
  5. using Products.Common.Dtos;
  6. using Products.Common.Exceptions;
  7. namespace Products.Backoffice.Controllers;
  8. public class ProductController : Controller
  9. {
  10. private readonly IProductService _productService;
  11. public ProductController(IProductService productService)
  12. {
  13. _productService = productService;
  14. }
  15. // GET
  16. public IActionResult Index()
  17. {
  18. var products = _productService.GetProducts();
  19. return View(products);
  20. }
  21. // GET /product/1
  22. public IActionResult Details(int id)
  23. {
  24. var product = _productService.GetProduct(id);
  25. return View(product);
  26. }
  27. public IActionResult Create()
  28. {
  29. return View();
  30. }
  31. [HttpPost]
  32. public IActionResult Create(CreateProductDto productDto)
  33. {
  34. if (!ModelState.IsValid)
  35. {
  36. return View(productDto);
  37. }
  38. _productService.AddProduct(productDto);
  39. return RedirectToAction(nameof(Index));
  40. }
  41. public IActionResult Edit(int id)
  42. {
  43. var product = _productService.GetProduct(id);
  44. return View(product);
  45. }
  46. [HttpPost]
  47. public IActionResult Edit(int id, ProductDto productDto)
  48. {
  49. if (!ModelState.IsValid)
  50. {
  51. return View(productDto);
  52. }
  53. _productService.UpdateProduct(id, new UpdateProductDto()
  54. {
  55. Name = productDto.Name,
  56. Brand = productDto.Brand,
  57. Color = productDto.Color
  58. });
  59. return RedirectToAction(nameof(Index));
  60. }
  61. public IActionResult Delete(int id)
  62. {
  63. try
  64. {
  65. _productService.DeleteProduct(id);
  66. }
  67. catch (Exception e)
  68. {
  69. return e is RecordNotFoundException ? NotFound() : StatusCode(500);
  70. }
  71. return RedirectToAction(nameof(Index));
  72. }
  73. [Route("Error/{statusCode:int}")]
  74. public IActionResult Error(int statusCode)
  75. {
  76. var feature = HttpContext.Features.Get<IStatusCodeReExecuteFeature>();
  77. return View(new ErrorViewModel { StatusCode = statusCode, OriginalPath = feature?.OriginalPath });
  78. }
  79. }