Monday, 18 September 2017

Passing Antiforgery token in Ajax

Controller have function like

[HttpPost]
[ValidateAntiForgeryToken]
 public JsonResult ActionName(int Id)
{
    //do your stuff
}

Cshtml Page 

@Html.AntiForgeryToken()
<!--Include ajax script render section for ajax call--> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>

<script>
 $.ajax({
                    url: '../Controllername/ActionName',
                    type: "Post",
                   data: {
__RequestVerificationToken: $('input[name="__RequestVerificationToken"]').val(),
Id: 1},
                    success: function (response) {
                      //do your stuff
                    },
                    error: function (errorcode, textStatus, errorThrown) {
                        // alert("Error '" + errorcode.status + "' (textStatus: '" + textStatus + "', errorThrown: '" + errorThrown + "')");
                    },
                    complete: function () {
                        // do your stuff after complete                    }
                });
</script>

No comments:

Post a Comment