Despite my experience with ajax in razor pages, I am struggling to understand why this particular script is not functional. Each time I run it, I encounter a 400 error in the developer tools. It appears that the page handler is not being reached at all.
<script>
$.ajax({
url: "/Account/Users/Index?handler=Delete",
type: "POST",
data: {
id: id
},
success: function () {
swal("User Disabled!", {
icon: "success",
});
},
error: function (xhr, ajaxOptions, thrownError) {
swal("Failed to connect to server. Please try again later.");
}
});
</script>
Concerning the page handler:
public async Task<IActionResult> OnPostDeleteAsync(int? id)
{
if (id == null)
{
return NotFound();
}
var user = await _context.Users.FindAsync(id);
if (user != null)
{
user.IsActivo = false;
_context.Users.Attach(user).Property( u => u.IsActivo).IsModified = true;
await _context.SaveChangesAsync();
}
return RedirectToPage("./Index");
}
I have experimented with different URL variations, but none seem to be effective. I am unable to identify any errors within the code...
EDIT
It appears that the issue may lie within the validation of the anti-forgery token on the razor page.
After adding Ignore Anti forgery Token to the page model, the script now runs smoothly.