所需的防伪表单字段__requestverificationtoken不存在ajax调用时出错

时间:2015-05-22 10:35:49

标签: javascript jquery ajax asp.net-mvc

  

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

上面的所有答案都没有帮助我。我在使用Jquery Ajax调用的请求中收到此错误:

  

"所需的防伪表格字段" __ RequestVerificationToken"是   不存在"

如果我在POST操作方法中评论[ValidateAntiForgeryToken]属性,它可以正常工作。我想知道为什么我收到这个错误。

@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 个答案:

答案 0 :(得分:0)

我总是在POST数据中包含请求验证令牌而不是标题。我会像这样接近它:

首先将type="submit"添加到您的输入按钮,以便在点击时提交表单。然后在你的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();
});