I'm implementing an example based on EF Core
and RazorPages
for performing simple CRUD.
Now specifically the 2nd page (Index.cshtml) representing the "List" view. Each row contains a button
element for deletion.
Snippet from Products.cshtml
<form method="POST">
@foreach(var product in Model.Products) {
<button type="submit" asp-page-handler="delete" asp-route-id="@product.Id">delete</button>
<!-- the one below doesn't work with my custom Javascript -->
<!-- <button data-confirm type="submit" asp-page-handler="delete" asp-route-id="@product.Id">delete</button> -->
}
</form>
Snippet from Products.cshtml.cs
public async Task<IActionResult> OnPostDeleteAsync(int id)
{
var product = await _db.Products.FindAsync(id);
if (product != null)
{
//_db.Products.Remove(product);
//await _db.SaveChangesAsync();
}
return RedirectToPage();
}
Up to this point it works. I can click the delete button and I see a successful redirect back to the page.
Now I want to add a custom confirmation functionality using Javscript. I can use jQuery in this context so I'm basically intercepting all data-confirm
attributes buttons and prevent the default action so I can submit only if the user confirms.
$('button[data-confirm]').each(function() {
var currentElement = this;
var currentForm = currentElement.form;
$(currentElement).click(function (e) {
e.preventDefault();
var confirmValue = $(currentElement).attr('data-confirm');
var confirmText = confirmValue ? confirmValue : 'Are you sure?';
bootbox.confirm(confirmText, function (result) {
if (result) {
currentForm.submit();
}
});
});
});
With my new functionality the RazorPage
mechanism doesn't call OnPostDeleteAsync
... How should I submit the form "manually" to comply with RazorPages submits?
I basically had to account for the generated formaction
attribute on the button
element. Setting this value as the form action made it work.
$('button[data-confirm]').each(function() {
var currentElement = this;
var currentForm = currentElement.form;
$(currentElement).click(function (e) {
e.preventDefault();
var confirmValue = $(currentElement).attr('data-confirm');
var confirmText = confirmValue ? confirmValue : 'Are you sure?';
var formAction = $(currentElement).attr('formaction'); //ADDED THIS LINE
bootbox.confirm(confirmText, function (result) {
if (result) {
currentForm.action = formAction; //ADDED THIS LINE
currentForm.submit();
}
});
});
});