showing results for - "antiforgerytoken mvc with ajax"
Clara
05 Jan 2019
1@using (Html.BeginForm(null, null, FormMethod.Post, new { id = "__AjaxAntiForgeryForm" }))
2{
3    @Html.AntiForgeryToken()
4}
5
6<div id="myDiv" data-url="@Url.Action("Index", "Home")">
7    Click me to send an AJAX request to a controller action
8    decorated with the [ValidateAntiForgeryToken] attribute
9</div>
10
11<script type="text/javascript">
12    $('#myDiv').submit(function () {
13        var form = $('#__AjaxAntiForgeryForm');
14        var token = $('input[name="__RequestVerificationToken"]', form).val();
15        $.ajax({
16            url: $(this).data('url'),
17            type: 'POST',
18            data: { 
19                __RequestVerificationToken: token, 
20                someValue: 'some value' 
21            },
22            success: function (result) {
23                alert(result.someValue);
24            }
25        });
26        return false;
27    });
28</script>
Max
09 Nov 2019
1
2
3        function DeletePersonel(id) {
4
5                var data = new FormData();
6                data.append("__RequestVerificationToken", "@HtmlHelper.GetAntiForgeryToken()");
7
8                $.ajax({
9                    type: 'POST',
10                    url: '/Personel/Delete/' + id,
11                    data: data,
12                    cache: false,
13                    processData: false,
14                    contentType: false,
15                    success: function (result) {
16
17                    }
18                });
19
20        }
21    
22
23        public static class HtmlHelper
24        {
25            public static string GetAntiForgeryToken()
26            {
27                System.Text.RegularExpressions.Match value = System.Text.RegularExpressions.Regex.Match(System.Web.Helpers.AntiForgery.GetHtml().ToString(), "(?:value=\")(.*)(?:\")");
28                if (value.Success)
29                {
30                    return value.Groups[1].Value;
31                }
32                return "";
33            }
34        }
35