Search code examples
c#ajaxasp.net-corerazor

Ajax post to Razor page backend not working


I need to post an id from my view to the back end razor page and im not sure what i'm doing wrong i keep getting 404 error. Here is my code :

public async Task<IActionResult> DeleteHourLine(int? id)
    {
        HourEntryModel hourEntryModel = _context.HourEntryModel.Where(m => m.ID == 
        id).FirstOrDefault();
        _context.HourEntryModel.Remove(hourEntryModel);
        await _context.SaveChangesAsync();

        return new RedirectToPageResult("Index");
    }

Ajax:

 function DeleteHourLine(obj)
    {
        var ele = $(obj);
        var id = ele.data("model-id");
      
        $.ajax({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            url: '?handler=DeleteHourLine',
            data: { int: id },
            success: function (data) {
                ele.closest("tr").remove();
            },
            error: function (result) {
                alert("fail");
            }
        })
    }

HTML razor code:

            <td>
                <img id="DeleteHourLine" onclick="DeleteHourLine(this)" data-model-id="@item.ID" 
                src="~/delete-16.png" />
            </td>

Solution

  • Firstly,you need to change DeleteHourLine to OnPostDeleteHourLineAsync.The default convention works by matching the HTTP verb used for the request to the name of the method, which is prefixed with "On": OnGet(), OnPost(), OnPut() etc.And you can add Async suffix on methods that contain asynchronous code.

    And you need to remove contentType: "application/json; charset=utf-8",,because you don't post data in body.

    Then you need to change data: { int: id }, to data: { id: id },,because you use int? id in handler.

    Last but not least,you need to add @Html.AntiForgeryToken() to your page,and add headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() }, to your ajax.Razor Pages are designed to be protected from (CSRF/XSRF) attacks,so Antiforgery token generation and validation are automatically included in Razor Pages.

    Here is a demo:

    view(I use 1 as sample data,and add @Html.AntiForgeryToken() so that can get antiforgery token in the view):

    <td>
        <img id="DeleteHourLine" onclick="DeleteHourLine(this)" data-model-id="1"
             src="~/imgs/2.jpg" />
    </td>
    @Html.AntiForgeryToken()
    

    ajax:

    function DeleteHourLine(obj) {
            var ele = $(obj);
            var id = ele.data("model-id");
    
            $.ajax({
                type: "POST",
                url: '?handler=DeleteHourLine',
                headers: { "RequestVerificationToken": $('input[name="__RequestVerificationToken"]').val() },
                data: { id: id },
                success: function (data) {
                    ele.closest("tr").remove();
                },
                error: function (result) {
                    alert("fail");
                }
            })
        }
    

    handler:

    public async Task<IActionResult> OnPostDeleteHourLineAsync(int? id)
            {
                
                return new RedirectToPageResult("Index");
            }
    

    result: enter image description here