gpt4 book ai didi

javascript - ASP.NET MVC Ajax 提交带有 AntiforgeryToken 的表单和带有验证的序列化表单数据

转载 作者:行者123 更新时间:2023-11-30 14:25:27 25 4
gpt4 key购买 nike

我正在尝试像这样通过 ajax 提交表单:

$(document).ready(function () {
$("#form").submit(function (e) {
e.preventDefault();
var token = $('input[name="__RequestVerificationToken"]', this).val();
var form_data = $(this).serialize();
$.ajax({
url: "@Url.Action("SaveRole", @ViewContext.RouteData.Values["controller"].ToString())",
method: "POST",
data: form_data,
contentType: "application/json",
success: function (result) {
console.log(result);
},
error: function (error) {
console.log(error);
}
});
return false;
console.log(form_data);
});
});

这联系了这个 Controller :

    [HttpPost]
[ValidateAjax]
[ValidateAntiForgeryToken]
public ActionResult SaveRole(SaveRolesDetailsViewModel Input)
{
//var role = rolesData.GetByName(Input);
var result = this.Json(new
{
Output = Input
}, JsonRequestBehavior.DenyGet);
return result;
}

现在,我收到错误消息,指出我的 RequestVerificationToken 字段未提交,但我不确定如何将它与我的表单数据结合起来。默认情况下,当我序列化我的表单数据时,它已经发送了这个 token ,但由于某种原因我的 Controller 仍然失败。

此外,我如何使用模型状态来显示我的表单验证?现在它们作为 json 对象返回。

编辑:

AjaxValidate 属性:

public class ValidateAjax : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (!filterContext.HttpContext.Request.IsAjaxRequest())
return;

var modelState = filterContext.Controller.ViewData.ModelState;
if (!modelState.IsValid)
{
var errorModel =
from x in modelState.Keys
where modelState[x].Errors.Count > 0
select new
{
key = x,
errors = modelState[x].Errors.
Select(y => y.ErrorMessage).
ToArray()
};
filterContext.Result = new JsonResult()
{
Data = errorModel
};
filterContext.HttpContext.Response.StatusCode = (int)HttpStatusCode.BadRequest;
}
}
}

当我提交一个空表单时,这是返回的内容:

0:{key: "RoleName", errors: ["The Role Name field is required."]}

最佳答案

当您使用 jQuery 时 .serialize()方法,它生成查询字符串格式(即 ..&name=value&... ,需要使用默认 contentType 发送 - 即 'application/x-www-form-urlencoded; charset=UTF-8'

删除 contentType: "application/json",来自 ajax 选项。

此外,您的 var token = $('input[name="__RequestVerificationToken"]', this).val();代码行不是必需的 - 使用 .serialize() 时包含 token

$("#form").submit(function (e) {
e.preventDefault();
// Add the following if you have enabled client side validation
if (!$(this).valid()) {
return;
}
var form_data = $(this).serialize();
$.ajax({
url: "@Url.Action("SaveRole")",
method: "POST",
data: form_data,
success: function (result) {
... // see notes below
},
error: function (error) {
console.log(error);
}
});
// return false; not necessary since you have used e.preventDefault()
console.log(form_data);
});

返回ModelState错误,删除你的 ValidateAjaxAttribute - 返回 BadRequest不合适(意在表明由于语法无效服务器无法理解请求)。

改为修改 POST 方法以返回 JsonResult包括错误(注意不需要返回模型)

public ActionResult SaveRole(SaveRolesDetailsViewModel Input)
{
if (ModelState.IsValid)
{
return Json(new { success = true });
}
else
{
var errors = ModelState.Keys.Where(k => ModelState[k].Errors.Count > 0).Select(k => new { propertyName = k, errorMessage = ModelState[k].Errors[0].ErrorMessage });
return Json(new { success = false, errors = errors });
}
}

然后在success回调中,如果有错误,循环遍历,找到对应的<span> @Html.ValidationMessageFor() 生成的元素并更新其内容和类名

success: function (result) {
if (result.success) {
return;
}
$.each(result.errors, function(index, item) {
// Get message placeholder
var element = $('[data-valmsg-for="' + item.propertyName + '"]');
// Update message
element.append($('<span></span>').text(item.errorMessage));
// Update class names
element.removeClass('field-validation-valid').addClass('field-validation-error');
$('#' + item.propertyName).removeClass('valid').addClass('input-validation-error');
});
},

关于javascript - ASP.NET MVC Ajax 提交带有 AntiforgeryToken 的表单和带有验证的序列化表单数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52016665/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com