0
Answer

Run C# Method on confirm bootstrap modal (to delete) Razor Pages

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<Producto> 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";
}

<h1>Lista de Productos</h1>

<a class="btn btn-primary mb-3" asp-page="CrearEditar" asp-route-id ="0">Agregar Nuevo Producto</a>

<table class="table table-striped">
    <thead>
        <tr>
            <th>Id</th>
            <th>Nombre</th>
            <th>Precio</th>
            <th>Stock</th>
            <th>Fecha Creación</th>
            <th>Acciones</th>
        </tr>
    </thead>
    <tbody>
    @foreach (var producto in Model.productos)
    {
        <tr>
            <td>@producto.Id</td>
            <td>@producto.Nombre</td>
            <td>@producto.Precio.ToString("C")</td>
            <td>@producto.Stock</td>
            <td>@producto.FechaCreación</td>
            <td>
                <a class="btn btn-secondary btn-sm" asp-page="CrearEditar" asp-route-id="@producto.Id">Editar</a>
                <button type="button" class="btn btn-danger btn-sm" id="openModalBtn" value="@producto.Id">Borrar</button>
                <a class="btn btn-info btn-sm" asp-page="Detalle" asp-route-id="@producto.Id">Detalle</a>
            </td>
        </tr>
        }
    </tbody>
</table>

<!-- Modal -->
<div class="modal fade" id="confirmationModal" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="staticBackdropLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h1 class="modal-title fs-5" id="staticBackdropLabel">Modal title</h1>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                ...
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancelar</button>
                <button type="button" class="btn btn-primary" id="confirmActionBtn">Borrar</button>
            </div>
        </div>
    </div>
</div>

<!-- A hidden form to submit the action -->
<form method="post" id="myForm" asp-page-handler="OnPostDeleteConfirm">
    <input type="hidden" name="paramName" id="paramNameInput" />
</form>

@section Scripts {
    <script>
        $(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();
            });
        });
    </script>
}

Any help is appreciated. If you need more information about this topic, please let me know. Thanks

Pablo