由于[ValidateAntiForgeryToken()]和已禁用Cookie,“提交”按钮未触及控制器

问题描述 投票:0回答:1

我正在使用@ Html.AntiForgeryToken(),但由于此代码,当我点击提交时,它不会在控制器中点击操作。

@using (Ajax.BeginForm("Action", "COntroller",null, new AjaxOptions { OnBegin = "$('#dvLoading').removeClass('displayNone');", OnSuccess = "ShowResultUpsID(data);", OnFailure = "$('#dvLoading').addClass('displayNone'); Showerror(); scrollToTop();" }, new { @id = "CreateID", @Name = "CreateID" }))
{
    @Html.AntiForgeryToken()

}

下面是我的行动

 [HttpPost]
 [ValidateAntiForgeryToken()]
 public ActionResult MyAction(Model object)
 {
 }

注意:禁用cookie。

asp.net-mvc antiforgerytoken
1个回答
0
投票

您需要将jquery.unobtrusive-ajax库添加到您的项目中。它可以帮助您使用Html Ajax表单。

<script src="~/Scripts/jquery-3.3.1.min.js"></script>
<script src="~/Scripts/jquery.unobtrusive-ajax.min.js"></script>

<script type="text/javascript">
    function OnSuccess(resolve) { console.log(resolve) }
    function OnFailure(error) { console.log(error) }
    function OnComplete(resolve) { console.log(resolve) }
</script>

@using (Ajax.BeginForm("AddUser", new AjaxOptions { HttpMethod = "POST", OnSuccess = "OnSuccess", OnComplete = "OnComplete", OnFailure = "OnFailure" }))
{
    @Html.AntiForgeryToken();
    @Html.HiddenFor(x => x.Id)
    @Html.TextBoxFor(x => x.FirstName)
    @Html.TextBoxFor(x => x.LastName)
    <button>Save</button>

}

[HttpPost, ValidateAntiForgeryToken]
public ActionResult AddUser(UserModel model)
{
   return Json(model, JsonRequestBehavior.AllowGet);
}
© www.soinside.com 2019 - 2024. All rights reserved.