asp.net mvc“所需的防伪表单字段”__ RequestVerificationToken“不存在。”

时间:2017-07-20 12:59:47

标签: jquery ajax asp.net-mvc

在我的部分视图中,我使用了一些jquery代码来提交我的表单。但是我收到了这个错误。The required anti-forgery form field"__RequestVerificationToken" is not present.如你所见,我在部分视图中添加了@Html.AntiForgeryToken()以及我在我的控制器上添加了[ValidateAntiForgeryToken]。但我又得到了错误。我已经阅读了StackOverflow中的所有问题,但他们无法帮助我。

@model Dentistry.Areas.ViewModels.UserViewModel

    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
            <span class="glyphicon glyphicon-remove" aria-hidden="true"></span>
        </button>
        <h4 class="modal-title custom_align" id="Heading">ویرایش کاربران</h4>

    </div>

    @if (Model != null && Model.UserId != string.Empty)
    {
        <div class="modal-body" id="editModal">
            <form id="#myForm">
              @Html.AntiForgeryToken()
                <div class="form-group">
                    @Html.HiddenFor(a => a.UserId)
                </div>
                <div class="form-group">
                    <label>نام کاربری</label>
                    @Html.TextBoxFor(a => a.UserName, new { @class = "form-control" })
                    @Html.ValidationMessageFor(a => a.UserName)
                </div>
                <div class="form-group">
                    <label>نام</label>
                    @Html.TextBoxFor(a => a.FirstName, new { @class = "form-control" })
                    @Html.ValidationMessageFor(a => a.FirstName)
                </div>

                <div class="form-group">
                    <label>نام خانوادگی</label>
                    @Html.TextBoxFor(a => a.LastName, new { @class = "form-control" })
                    @Html.ValidationMessageFor(a => a.LastName)
                </div>
                <div class="form-group">
                    <label>جنسیت</label>
                    @Html.TextBoxFor(a => a.Gender, new { @class = "form-control" })
                    @Html.ValidationMessageFor(a => a.Gender)
                </div>
                <div class="form-group">
                    <label>وضعیت</label>
                    @Html.TextBoxFor(a => a.IsActive, new { @class = "form-control" })
                    @Html.ValidationMessageFor(a => a.IsActive)
                </div>

                <div class="form-group">
                    <label>ایمیل</label>
                    @Html.TextBoxFor(a => a.Email, new { @class = "form-control" })
                    @Html.ValidationMessageFor(a => a.Email)
                </div>
                <div class="form-group">
                    <label>آدرس</label>
                    @Html.TextBoxFor(a => a.Address, new { @class = "form-control" })
                    @Html.ValidationMessageFor(a => a.Address)
                </div>
                <div class="form-group">
                    <label>شماره تماس</label>
                    @Html.TextBoxFor(a => a.PhoneNumber, new { @class = "form-control" })
                    @Html.ValidationMessageFor(a => a.PhoneNumber)
                </div>

                <a href="#" id="btnSubmit" class="btn btn-success btn-block">ویرایش</a>

            </form>


        </div>
    }
    <script>
        $(document).ready(function () {



            $("#btnSubmit").click(function () {
                var token = $('input[name="__RequestVerificationToken"]').val();
                var headers = {};
                // other headers omitted
                headers['__RequestVerificationToken'] = token;
                //  $('#loaderDiv').show();
                var myFormData = $("#myForm").serialize();
                console.log(myFormData);
                $.ajax({
                    cache:false,
                    type: "POST",
                    headers: headers,
                    url: "/Users/Edit",
                    dataType:"json",
                    data: myFormData,
                    success: function () {
                        //  $('#loaderDiv').hide();
                        $('#edit').modal('hide');
                        window.location.href = "/Users/Index";
                    }

                });

            });

        });
    </script>

===============================================

    [HttpPost]
    [ValidateAntiForgeryToken]
    // [Bind(Include = "UserID,UserName,PasswordHash,FirstName,LastName,Gender,Email,CreateDate,IsActive,Address,PhoneNumber")]
    public ActionResult Edit(UserViewModel user)
    {
        //
        //bool status=false;
        if (ModelState.IsValid)
        {
            var userQuery=db.User.SingleOrDefault(u => u.Id  == user.UserId);
            if (user.UserId != string.Empty)
            {
                userQuery.FirstName = user.FirstName;
                userQuery.LastName = user.LastName;
                userQuery.PhoneNumber = user.PhoneNumber;
                userQuery.UserName = user.UserName;
                userQuery.Email = user.Email;
                userQuery.Address = user.Address;
                userQuery.Gender = Convert.ToBoolean(user.Gender);
                userQuery.IsActive = Convert.ToBoolean(user.IsActive);
            }
            else
            {
                User userDB=new User();
                userDB = userQuery;
                db.User.Add(userDB);
            }
            //  db.Entry(user).State = EntityState.Modified;
            db.SaveChanges();
            //status = true;

        }
        return RedirectToAction("Index");
        // return View(user);
        // return new JsonResult { Data = new { status = status } };
    }

2 个答案:

答案 0 :(得分:3)

而不是使用客户端标记使用razor表单标记

 @using (Html.BeginForm("Action", "Controller", FormMethod.Post, new { id = "formID", @class = "form-horizontal" }))
       {

//formCode
} 

它看起来像

在客户端

$(function(){
     $('#formID').on('submit',function(e){
e.preventDefault();
     SubmitForm();
    })
})
  function SubmitForm() {
            var data = $("#RequestForm").serialize();
            var url = "/RequestManagement/ProcessRequest"
            var form = $('#RequestForm')[0]
            var formdata = false;
            if (window.FormData) {
                formdata = new FormData(form);
            }
            $.ajax({
                url: url,
                type: 'POST',
                dataType: 'json',
                data: formdata ? formdata : data,
                cache: false,
                contentType: false,
                //  enctype: 'multipart/form-data',
                processData: false,
                success: function (data) {
                    if (data == "SessionTimeout") {
                        window.location.href = "/Account/Relogin";
                    }

我的表单就像

    @using (Html.BeginForm("ProcessRequest", "RequestManagement", FormMethod.Post, new { id = "RequestForm", @class = "form-horizontal" }))
    {
        @Html.AntiForgeryToken();
        <div class="box-body">
            <div class="form-group">
                <label for="selectStatus" class="col-sm-2 control-label">Status :</label>
                <div class="col-sm-10">
                    <select class="form-control" name="StatusID" id="selectStatus" data-val="true" data-val-required="Please select a Status.">
                        <option value="" selected="selected">--Select Status--</option>
                    </select>
                    <span data-valmsg-for="StatusID" data-valmsg-replace="true"></span>
                    <input type="hidden" name="StatusName" id="statusName" />
                </div>
            </div>
            <div class="form-group">
                <label for="textComment" class="col-sm-2 control-label">Comment :</label>

                <div class="col-sm-10">
                    <textarea class="form-control" name="Comment" id="textComment" style="resize:none;" placeholder="Comment" rows="3" data-val="true" data-val-required="Please enter a Comment."></textarea>
                    <span data-valmsg-for="Comment" data-valmsg-replace="true"></span>
                </div>
            </div>
            <input type="hidden" name="RequestID" id="requestIDHolder" required />
        </div>
        <div class="box-footer"></div>
        <!-- /.box-body -->
        <div class="modal-footer">
            <button type="submit" class="btn btn-info">Save</button>
            <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
        </div>

    }

答案 1 :(得分:0)

您正在将防伪令牌放入请求标头中。只需将其添加到您要发布的表单数据对象中:

myFormDatadata.__RequestVerificationToken = token;