1
votes

I've done so many ajax in razor pages but i can't figure out why this does not work. It keeps giving me error 400 on dev tools. It does not reach the page handler no matter what.

<script>
     $.ajax({
                    url: "/Account/Users/Index?handler=Delete",
                    type: "POST",
                    data: {
                        id: id
                    },
                    success: function () {
                        swal("Utilizador Desactivado!", {
                            icon: "success",
                        });
                    },
                    error: function (xhr, ajaxOptions, thrownError) {
                        swal("Falha na ligação ao servidor. Tente novamente mais tarde.");
                    }
                });
</script>

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 tried many url combinations and none work. I don't see what is wrong in here....

EDIT

It seems like the problem is the anti forgery token not being validated on razor page.

I wrote Ignore Anti forgery Token on the page model and everything works correctly

2
What exactly does "does not work" mean here? If you debug what's happening?Ben
it does not reach the page handler, just gives error 400 on dev tools on browserJackal

2 Answers

3
votes

As you've already found out it's the anti forgery token, that is ruining your day. Now, if you are inside a form, asp.net core will create a hidden input with that token for you. If you are not working with a form on your page, you'll have to call @Html.AntiForgeryToken(), which will add the token for you. Still, this will not resolve the Bad Request for you. You have to add it to your ajax call:

$.ajax({
    url: "/Account/Users/Index?handler=Delete",
    type: "POST",
    beforeSend: function (xhr) {
        xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val());
    },
    data: {
        id: id
    },
});

Additionally, add this line to your Startup.cs file:

services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN");
1
votes

I don't know what you mapping of URL use, but as usual it consists of controllerName/actionName/. In your case try to use:

url: "/Account/OnPostDeleteAsync"

or

url: "/Users/OnPostDeleteAsync" but if your URL is correct, then try to use [FromForm] attribute

public async Task<IActionResult> OnPostDeleteAsync([FromForm]int? id)

I hope this will help