How to include the @Html.AntiForgeryToken() when deleting an object using a Delete link

后端 未结 2 1116
轮回少年
轮回少年 2020-12-29 10:00

i have the following ajax.actionlink which calls a Delete action method for deleting an object:-

 @if (!item.IsAlreadyAssigned(item         


        
2条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-29 10:32

    You need to use the Html.AntiForgeryToken helper which sets a cookie and emits a hidden field with the same value. When sending the AJAX request you need to add this value to the POST data as well.

    So I would use a normal link instead of an Ajax link:

    @Html.ActionLink(
        "Delete", 
        "Delete", 
        "LabTest", 
        new { 
            id = item.LabTestID
        }, 
        new { 
            @class = "delete",
            data_confirm = "Are You sure You want to delete (" + item.Description.ToString() + ") ?"
        }
    )
    

    and then put the hidden field somewhere in the DOM (for example before the closing body tag):

    @Html.AntiForgeryToken()
    

    and finally unobtrusively AJAXify the delete anchor:

    $(function () {
        $('.delete').click(function () {
            if (!confirm($(this).data('confirm'))) {
                return false;
            }
    
            var token = $(':input:hidden[name*="RequestVerificationToken"]');
            var data = { };
            data[token.attr('name')] = token.val();
            $.ajax({
                url: this.href,
                type: 'POST',
                data: data,
                success: function (result) {
    
                },
                error: function () {
    
                }
            });
    
            return false;
        });
    });
    

    Now you could decorate your Delete action with the ValidateAntiForgeryToken attribute:

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Delete(int id)
    {
        ...
    }
    

提交回复
热议问题