Hi Ladies and Guys,
I'm new to the forum. I'm working on an ASP.NET Core Razor Pages app. It's a CRUD. I was already able to implement Create and Edit in the same Razor page. I have a list of products (in Index.cshtml) and after the model fields on each row I have buttons for Edit and Delete. What I want is that when I click the Delete button, appears the bootstrap Modal and if I click the Confirm button in it, the C# POST method that is in the same Index page deletes the row (and the row in the DB). I took from Internet some Javascript and the Modal appears, but when I click the confirm button, the C# method is not called and the VS Debugger shows Model.productos in:
@foreach (var producto in Model.productos) { // here go the rows }as null (NullReferenceException), only productos, not Model.
Here are the relevant files in where the problem is.
First, the Index.cshtml.cs
namespace CrudProductos.Pages.Productos
{
public class IndexModel : PageModel
{
private readonly ApplicationDBContext _context;
public IList productos { get; set; }
public IndexModel(ApplicationDBContext context)
{
_context = context;
}
public void OnGet()
{
productos = _context.Producto.ToList();
}
public IActionResult OnPostDeleteConfirm(int id)
{
Producto Producto = _context.Producto.Find(id);
if (Producto == null)
{
return NotFound();
}
_context.Producto.Remove(Producto);
_context.SaveChanges();
return RedirectToPage("Index");
}
}
}And the Index.cshtml
@page
@model CrudProductos.Pages.Productos.IndexModel
@{
ViewData["Title"] = "Lista de Productos";
}
Lista de Productos
Agregar Nuevo Producto
Id
Nombre
Precio
Stock
Fecha Creación
Acciones
@foreach (var producto in Model.productos)
{
@producto.Id
@producto.Nombre
@producto.Precio.ToString("C")
@producto.Stock
@producto.FechaCreación
Editar
Borrar
Detalle
}
Modal title
...
Cancelar
Borrar
@section Scripts {
$(document).ready(function () {
var confirmationModal = new bootstrap.Modal(document.getElementById('confirmationModal'));
var confirmActionBtn = document.getElementById('confirmActionBtn');
var myForm = document.getElementById('myForm');
var paramNameInput = document.getElementById('paramNameInput');
var deleteBtn = document.getElementById('openModalBtn');
// Add event listener to the confirm button
confirmActionBtn.addEventListener('click', function () {
// Optional: set some data to be passed to the C# method
paramNameInput.value = document.getElementById('openModalBtn').value;
// Submit the hidden form, which triggers the server-side method
myForm.submit();
// Hide the modal after submission (optional, as the page may reload)
confirmationModal.hide();
});
deleteBtn.addEventListener('click', function() {
confirmationModal.show();
});
});
}Any help is appreciated. If you need more information about this topic, please let me know. Thanks
Pablo

Answers
Know the answer? Post it. Somebody with the same question will find it here.