0
votes

I need to remove an item in Cart with razor page. For this i used a form with asp-page-handler.

Cart.cshtml :

<td class="text-center">
            <form asp-page-handler="Remove" method="post">
                <input type="hidden" name="id" value="@line.Product.Id" />
                <input type="hidden" name="returnUrl" value="@Model.ReturnUrl" />
                <button type="submit" class="btn btn-sm btn-danger">
                    Remove
                </button>
            </form>
</td>

And my Cart.html.cs has a OnPostRemove method like this:

public IActionResult OnPostRemove(int id, string returnUrl)
    {
        Cart.RemoveLine(Cart.Lines.First(cl =>
            cl.Product.Id == id).Product);
        return RedirectToPage(new { returnUrl = returnUrl });
    }

When i cliked remove button i got a 400 Error and my OnPostRemove method doesn't trigger.

Update

I included tag helper in my _ViewImports.cshtml and issue resolved.

@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers
2
Hi @İsmetKonuç, any updates about this case? Have you resolved the issue?Fei Han
I included tag helper in my _ViewImports.cshtml and issue resolved.İsmet Konuç
If not adding the @addTagHelper directive to the_ViewImports.cshtml file, the form tag with asp-page-handler will not be rendered well, which might cause 500 error, are you sure it cause 400 error?Fei Han
And if you checked the actual request with the posted data in F12 developer tool Network tab as I suggested, you would find handler name is not included in query string or route data of request URL if Tag Helpers are not available to the view.Fei Han

2 Answers

0
votes

Put the page handler inside the submit button tags.

<form method="post">
    ...
    <button type="submit" asp-page-handler="Remove">
        Remove
    </button>
</form>
0
votes

The code snippet that you shared seems ok, which work well with testing data on my side.

enter image description here

When i cliked remove button i got a 400 Error and my OnPostRemove method doesn't trigger.

To troubleshoot the issue, please check the actual request with the posted data in F12 developer tool Network tab.

And please note that if the antiforgery token validation is enabled, but the request does not include a valid antiforgery token or something wrong with the antiforgery cookies, which would also cause 400 Bad Request error.

For testing purpose, you can try to skip antiforgery token validation by applying IgnoreAntiforgeryTokenAttribute on page model class, then check if the request can be handled as expected.

[IgnoreAntiforgeryToken]
public class CartModel : PageModel
{