【发布时间】:2018-08-25 11:03:59
【问题描述】:
我正在尝试通过这样的 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);
});
});
这会联系这个控制器:
[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 字段未提交的错误,但我不确定如何将它与我的表单数据结合起来。默认情况下,当我序列化表单数据时,它已经发送了这个令牌,但由于某种原因我的控制器仍然失败。
另外,我如何使用模型状态来显示我的表单验证?现在它们作为 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."]}
【问题讨论】:
标签: javascript jquery asp.net asp.net-mvc