【发布时间】:2015-03-14 07:39:17
【问题描述】:
我在请求 Jquery Ajax 调用时收到此错误。
“所需的防伪表单字段“__RequestVerificationToken”不存在”
所以我找到了一些解决方案并应用了工作区,但发现它对我来说效果不佳。
我的请求电话:
$("#btn-save-survey").click(function (e) {
e.preventDefault();
var validationForm = $('#surveyForm').valid();
if (!validationForm) {
//$btn.button('reset');
//$("#loadingSaveSampling").addClass('hidden');
return;
}
var token = $('#surveyForm input[name="__RequestVerificationToken"]').val();
var dataRequest = JSON.stringify(
{
"__RequestVerificationToken": token,
"v1": $("v1").val(),
"v2": $("v2").val(),
"v3": $("v3").val(),
"v4":$("v4").val(),
"v5": $("v5").val(),
"v6": $("v6").val()
});
$.ajax({
type: "POST",
url: $("#url-xx").val() + "/test/xxxx",
data: dataRequest,
dataType: "json",
contentType: "application/json",
success: function (response) {
alert("sucesso=> " + response);
},
error: function (response) {
alert("erro=> " + response);
}
});
我的行动结果:
HttpPost]
[Route("criar-pesquisa")]
[ValidateAntiForgeryToken]
[ValidateAjax]
public ActionResult Create([Bind(Exclude = "SurveyId")]SurveyForm form)
{
try
{
if (ModelState.IsValid)
{
AddOrUpdateSurvey(form);
return Json(new { Success = true });
//return RedirectToRoute(Routes.SamplingSurvey);
}
else
{
var modelStateErrors = ModelState.Values.SelectMany(x => x.Errors).Select(y => y.ErrorMessage);
return Json(new { status = false, errorMessage = modelStateErrors, stackError = "" }, JsonRequestBehavior.AllowGet);
}
}
catch (DataException dex)
{
ModelState.AddModelError(dex.Message, "Houve um erro para salvar a pesquisa. Tente novamente mais tarde.");
return Json(new { status = false, errorMessage = dex.Message, stackError = dex.StackTrace }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new { status = false, errorMessage = ex.Message, stackError = ex.StackTrace }, JsonRequestBehavior.AllowGet);
}
}
我的表单我使用 forgeryToke 之类的:
@using (Html.BeginCreateSurveyForm(new { role = "form", id = "myForm" }))
{
@Html.AntiForgeryToken()
@Html.HiddenFor(m => m.id)
【问题讨论】:
标签: c# jquery model-view-controller antiforgerytoken