Advertisement
Ousterfort

ProductosController

Feb 6th, 2025
40
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 11.64 KB | Source Code | 0 0
  1. using System.Data;
  2. using ejemplo_crud_MVC_sqlServer.Models;
  3. using Microsoft.AspNetCore.Mvc;
  4. using Microsoft.Data.SqlClient;
  5.  
  6. namespace ejemplo_crud_MVC_sqlServer.Controllers
  7. {
  8.     public class ProductosController : Controller
  9.     {
  10.         private readonly string _connectionString;
  11.  
  12.         public ProductosController(IConfiguration configuration)
  13.         {
  14.             _connectionString = configuration.GetConnectionString("DefaultConnection");
  15.         }
  16.  
  17.         public IActionResult Index(int pagina = 1, int tamañoPagina = 10)
  18.         {
  19.             var productos = ObtenerProductos(pagina, tamañoPagina);
  20.  
  21.             var totalProductos = ObtenerTotalProductos();
  22.  
  23.             ViewBag.TotalPaginas = (int)Math.Ceiling((double)totalProductos / tamañoPagina);
  24.  
  25.             ViewBag.PaginaActual = pagina;
  26.  
  27.             return View(productos);
  28.         }
  29.  
  30.         private int ObtenerTotalProductos()
  31.         {
  32.             int totalProductos = 0;
  33.  
  34.             using (var connection = new SqlConnection(_connectionString))
  35.             {
  36.                 connection.Open();
  37.                 var command = new SqlCommand("sp_CRUD_General", connection)
  38.                 {
  39.                     CommandType = CommandType.StoredProcedure
  40.                 };
  41.                 command.Parameters.AddWithValue("@accion", "count");
  42.                 command.Parameters.AddWithValue("@tabla", "producto");
  43.                 command.Parameters.AddWithValue("@id", DBNull.Value);
  44.                 command.Parameters.AddWithValue("@pagina", DBNull.Value);
  45.                 command.Parameters.AddWithValue("@tamañoPagina", DBNull.Value);
  46.  
  47.                 using (var reader = command.ExecuteReader())
  48.                 {
  49.                     if (reader.Read())
  50.                     {
  51.                         totalProductos = (int)reader["TotalProductos"];
  52.                     }
  53.                 }
  54.             }
  55.  
  56.             return totalProductos;
  57.         }
  58.  
  59.         private List<Producto> ObtenerProductos(int pagina, int tamañoPagina)
  60.         {
  61.             var productos = new List<Producto>();
  62.  
  63.             using (var connection = new SqlConnection(_connectionString))
  64.             {
  65.                 connection.Open();
  66.                 var command = new SqlCommand("sp_CRUD_General", connection)
  67.                 {
  68.                     CommandType = CommandType.StoredProcedure
  69.                 };
  70.                 command.Parameters.AddWithValue("@accion", "select");
  71.                 command.Parameters.AddWithValue("@tabla", "producto");
  72.                 command.Parameters.AddWithValue("@id", DBNull.Value);
  73.                 command.Parameters.AddWithValue("@pagina", pagina);
  74.                 command.Parameters.AddWithValue("@tamañoPagina", tamañoPagina);
  75.  
  76.                 using (var reader = command.ExecuteReader())
  77.                 {
  78.                     while (reader.Read())
  79.                     {
  80.                         productos.Add(new Producto
  81.                         {
  82.                             idProducto = (int)reader["IdProducto"],
  83.                             nombreProducto = reader["NombreProducto"].ToString(),
  84.                             idCategoria = (int)reader["IdCategoria"],
  85.                             descripcion = reader["Descripcion"].ToString(),
  86.                             Categoria = new Categoria
  87.                             {
  88.                                 idCategoria = (int)reader["IdCategoria"],
  89.                                 nombreCategoria = reader["NombreCategoria"].ToString()
  90.                             }
  91.                         });
  92.                     }
  93.                 }
  94.             }
  95.  
  96.             return productos;
  97.         }
  98.  
  99.         private List<Categoria> ObtenerCategorias()
  100.         {
  101.             var categorias = new List<Categoria>();
  102.  
  103.             using (var connection = new SqlConnection(_connectionString))
  104.             {
  105.                 connection.Open();
  106.                 var command = new SqlCommand("sp_CRUD_General", connection)
  107.                 {
  108.                     CommandType = CommandType.StoredProcedure
  109.                 };
  110.                 command.Parameters.AddWithValue("@accion", "select");
  111.                 command.Parameters.AddWithValue("@tabla", "categoria");
  112.                 command.Parameters.AddWithValue("@id", DBNull.Value);
  113.                 command.Parameters.AddWithValue("@pagina", DBNull.Value);
  114.                 command.Parameters.AddWithValue("@tamañoPagina", DBNull.Value);
  115.  
  116.                 using (var reader = command.ExecuteReader())
  117.                 {
  118.                     while (reader.Read())
  119.                     {
  120.                         categorias.Add(new Categoria
  121.                         {
  122.                             idCategoria = (int)reader["IdCategoria"],
  123.                             nombreCategoria = reader["NombreCategoria"].ToString()
  124.                         });
  125.                     }
  126.                 }
  127.             }
  128.  
  129.             return categorias;
  130.         }
  131.  
  132.         public IActionResult CrearOEditar(int? id)
  133.         {
  134.             ViewBag.Categorias = ObtenerCategorias();
  135.  
  136.             if (!id.HasValue)
  137.             {
  138.                 return View(new Producto());
  139.             }
  140.  
  141.             var producto = ObtenerProductoPorId(id.Value);
  142.             if (producto == null)
  143.             {
  144.                 return NotFound();
  145.             }
  146.  
  147.             return View(producto);
  148.         }
  149.  
  150.         private Producto ObtenerProductoPorId(int idProducto)
  151.         {
  152.             Producto producto = null;
  153.  
  154.             using (var connection = new SqlConnection(_connectionString))
  155.             {
  156.                 connection.Open();
  157.                 var command = new SqlCommand("sp_CRUD_General", connection)
  158.                 {
  159.                     CommandType = CommandType.StoredProcedure
  160.                 };
  161.                 command.Parameters.AddWithValue("@accion", "select");
  162.                 command.Parameters.AddWithValue("@tabla", "producto");
  163.                 command.Parameters.AddWithValue("@id", idProducto);
  164.  
  165.                 using (var reader = command.ExecuteReader())
  166.                 {
  167.                     if (reader.Read())
  168.                     {
  169.                         producto = new Producto
  170.                         {
  171.                             idProducto = (int)reader["IdProducto"],
  172.                             nombreProducto = reader["NombreProducto"].ToString(),
  173.                             idCategoria = (int)reader["IdCategoria"],
  174.                             descripcion = reader["Descripcion"].ToString(),
  175.                             Categoria = new Categoria
  176.                             {
  177.                                 idCategoria = (int)reader["IdCategoria"],
  178.                                 nombreCategoria = reader["NombreCategoria"].ToString()
  179.                             }
  180.                         };
  181.                     }
  182.                 }
  183.             }
  184.  
  185.             return producto;
  186.         }
  187.  
  188.         [HttpPost]
  189.         public IActionResult CrearOEditar(Producto producto)
  190.         {
  191.             int filasAfectadas = 0;
  192.             try
  193.             {
  194.                 using (var connection = new SqlConnection(_connectionString))
  195.                 {
  196.                     connection.Open();
  197.                     using (var command = new SqlCommand("sp_CRUD_General", connection))
  198.                     {
  199.                         command.CommandType = CommandType.StoredProcedure;
  200.  
  201.                         string accion = producto.idProducto == 0 ? "insert" : "update";
  202.                         command.Parameters.AddWithValue("@accion", accion);
  203.                         command.Parameters.AddWithValue("@tabla", "producto");
  204.                         command.Parameters.AddWithValue("@id", producto.idProducto == 0 ? (object)DBNull.Value : producto.idProducto);
  205.                         command.Parameters.AddWithValue("@nombre", producto.nombreProducto);
  206.                         command.Parameters.AddWithValue("@descripcion", producto.descripcion);
  207.                         command.Parameters.AddWithValue("@idCategoria", producto.idCategoria);
  208.  
  209.                         command.Parameters.AddWithValue("@pagina", DBNull.Value);
  210.                         command.Parameters.AddWithValue("@tamañoPagina", DBNull.Value);
  211.  
  212.                         var returnParam = new SqlParameter
  213.                         {
  214.                             Direction = ParameterDirection.ReturnValue,
  215.                             SqlDbType = SqlDbType.Int
  216.                         };
  217.                         command.Parameters.Add(returnParam);
  218.  
  219.                         command.ExecuteNonQuery();
  220.  
  221.                         filasAfectadas = (int)returnParam.Value;
  222.                     }
  223.                 }
  224.  
  225.                 if (filasAfectadas > 0)
  226.                 {
  227.                     TempData["SuccessMessage"] = "Producto guardado exitosamente.";
  228.                 }
  229.                 else if (filasAfectadas == 0)
  230.                 {
  231.                     TempData["ErrorMessage"] = "No se realizaron cambios en el producto.";
  232.                 }
  233.                 else
  234.                 {
  235.                     TempData["ErrorMessage"] = "Ocurrió un error al guardar el producto.";
  236.                 }
  237.             }
  238.             catch (Exception ex)
  239.             {
  240.                 TempData["ErrorMessage"] = "Ocurrió un error inesperado: " + ex.Message;
  241.             }
  242.  
  243.             return RedirectToAction("Index");
  244.         }
  245.  
  246.         public IActionResult Eliminar(int id)
  247.         {
  248.             int filasAfectadas = 0;
  249.             try
  250.             {
  251.                 using (var connection = new SqlConnection(_connectionString))
  252.                 {
  253.                     connection.Open();
  254.                     using (var command = new SqlCommand("sp_CRUD_General", connection))
  255.                     {
  256.                         command.CommandType = CommandType.StoredProcedure;
  257.  
  258.                         command.Parameters.AddWithValue("@accion", "delete");
  259.                         command.Parameters.AddWithValue("@tabla", "producto");
  260.                         command.Parameters.AddWithValue("@id", id);
  261.  
  262.                         command.Parameters.AddWithValue("@nombre", DBNull.Value);
  263.                         command.Parameters.AddWithValue("@descripcion", DBNull.Value);
  264.                         command.Parameters.AddWithValue("@idCategoria", DBNull.Value);
  265.                         command.Parameters.AddWithValue("@pagina", DBNull.Value);
  266.                         command.Parameters.AddWithValue("@tamañoPagina", DBNull.Value);
  267.  
  268.                         var returnParam = new SqlParameter
  269.                         {
  270.                             Direction = ParameterDirection.ReturnValue,
  271.                             SqlDbType = SqlDbType.Int
  272.                         };
  273.                         command.Parameters.Add(returnParam);
  274.  
  275.                         command.ExecuteNonQuery();
  276.  
  277.                         filasAfectadas = (int)returnParam.Value;
  278.                     }
  279.                 }
  280.  
  281.                 if (filasAfectadas > 0)
  282.                 {
  283.                     TempData["SuccessMessage"] = "Producto eliminado exitosamente.";
  284.                 }
  285.                 else if (filasAfectadas == 0)
  286.                 {
  287.                     TempData["ErrorMessage"] = "No se encontró el producto a eliminar.";
  288.                 }
  289.                 else
  290.                 {
  291.                     TempData["ErrorMessage"] = "Ocurrió un error al eliminar el producto.";
  292.                 }
  293.             }
  294.             catch (Exception ex)
  295.             {
  296.                 TempData["ErrorMessage"] = "Ocurrió un error inesperado: " + ex.Message;
  297.             }
  298.  
  299.             return RedirectToAction("Index");
  300.         }
  301.     }
  302. }
  303.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement