Requested form field for forging __requestverificationtoken is missing Error in ajax call

form field to forge "__RequestVerificationToken" is not present when using jQuery Ajax and Html.AntiForgeryToken ()
How to make ajax request with anti-forgery token in mvc
Posting AJAX ValidateAntiForgeryToken without form for MVC action method

All answers above didn't work for me. I am getting this error in my request with a Jquery Ajax call:

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

If I comment out the attribute [ValidateAntiForgeryToken]

on the POST action method, it works 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>

      

+3


source to share


1 answer


I've always included the request validation token in the POST data, not the headers. I would approach like this:

First add type="submit"

to your enter button so that it submits 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();
});

      

0


source







All Articles