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

时间:2019-03-30 12:17:58

标签: asp.net-mvc antiforgerytoken

我正在使用@ 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。

1 个答案:

答案 0 :(得分: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);
}