3
votes

anti-forgery form field “__RequestVerificationToken” is not present when using jQuery Ajax and the Html.AntiForgeryToken()
How to make ajax request with anti-forgery token in mvc
AJAX Posting ValidateAntiForgeryToken without Form to MVC Action Method

All the answers above did not help me. I get this error in my request with Jquery Ajax call:

"The required anti-forgery form field "__RequestVerificationToken" is not present"

If I comment [ValidateAntiForgeryToken] attribute at POST action method it is working fine. I want to know why I am getting this error.

@using (Html.BeginForm("Save", "AddPost", FormMethod.Post, new { id = "CreateForm" }))
{
    @Html.AntiForgeryToken()

    <div class="form-horizontal">
        <h4>GropPost_Table</h4>
        <hr />
        @Html.ValidationSummary(true)

        <div class="form-group">
            @Html.LabelFor(model => model.Body, new { @class = "control-label col-md-2" })
            <div class="col-md-10">
                @Html.TextBoxFor(model => model.Body, new { id = "Bf" })
                @Html.ValidationMessageFor(model => model.Body)
            </div>
        </div>


        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <input id="btnAdd" value="Create" class="btn btn-default" />
            </div>
        </div>
    </div>
}  

  [HttpPost]
        [ValidateAntiForgeryToken]
        public JsonResult Save([Bind(Include = "Body")] GropPost_Table groppost_table)
        {

            if (ModelState.IsValid)
            {

                groppost_table.GroupID = 1;
                groppost_table.ID = 1;
                groppost_table.PostDate = System.DateTime.Now;
                db.GropPost_Table.Add(groppost_table);
                db.SaveChanges();
                return Json(groppost_table);
            }

            else
            {

                return Json("we Couldent add your post");
            }
        }

<script type="text/javascript">

    $("#btnAdd").click(function () {

        var GropPost_Table = {
            "Body": $("#Bf").val()       
        };

        var token = $('#CreateForm input[name=__RequestVerificationToken]').val()

        var headers = {};

        headers['__RequestVerificationToken'] = token;


        $.ajax( {
            type: "POST",
            url: "@Url.Action("Save","AddPost")",
            data: JSON.stringify(GropPost_Table),
            contentType: "application/json;charset=utf-8",
            processData: true,
            headers:headers,
            success: function (dataR) {
                $("#Bf").val('');
           },
            error: function (dataR) {
                $("#Bf").val('');
                alert(dataR.toString());
            }
        });
    });
    </script>
1
Your header setting is not using the right syntax - it should be an object with a key/value pair. Check the top answer in the second question you linked for an answer.Rory McCrossan
@RoryMcCrossan i edited my code! nothing changed ! still that error !Mohammad Olfatmiri

1 Answers

0
votes

I've alway included the Request Verification Token in the data of the POST and not the headers. I would approach it like this:

First add type="submit" to your input button so it will submit the form when clicked. Then in your javascript:

// Listen for the submit event on the form
$('#CreateForm').on('submit', function(event) { 
    var $form = $(this);

    $.ajax({
        // Html.BeginForm puts the url in the 
        // "action" attribute
        url: $form.attr('action'),
        // Serializing the form will pick up the verification
        // token as well as other input data
        data: $form.serialize(),
        success: function(dataR) {
            $('#Bf').val('');
        },
        error: function(dataR) {
            $('#Bf').val('');
            alert(dataR.toString());
        }
    });

    // Preventing the default action will keep the form
    // from doing a full POST.
    event.preventDefault();
});