我有一个 ASP.NET MVC 4 表单,其中有用于显示和隐藏一些 HTML 元素的复选框。访问表单页面时,RequestVerificationToken 值将正确创建为隐藏字段。某些 HTML 元素默认是隐藏的。
然后,在取消选中复选框(隐藏这些 HTML 元素)后,我勾选一个复选框以显示一些 HTML 元素,RequestVerificationToken 值消失。
因此,当我通过单击“创建”按钮提交表单时,出现以下错误:
The required anti-forgery form field "__RequestVerificationToken" is not present
如果我不取消选中该复选框,则 RequestVerificationToken 的值将存在并且表单将成功提交。
使用 jQuery/javascript 隐藏 HTML 元素。
为什么会发生这种情况?我该如何解决这个问题?在线研究错误仅建议添加以下属性。
我已经在 Create 操作方法中添加了属性,但没有在 GET 方法中添加:
// POST: /Document/Create
[HttpPost]
[ValidateAntiForgeryToken]
...
在创建表单页面中我还添加了:
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
...
这是显示和隐藏元素的 Javascript:
$('div.section .input_control').change(function () {
var $target = $(this).closest('div').find('.showSection');
if (this.checked) {
$target.show();
} else {
if (confirm("Are you sure you want to exclude this section?") == true) {
$target.hide();
jQuery(':hidden').val('');
} else {
$(this).prop("checked", true);
}
}
});
最佳答案
使用 jQuery .not()。 http://api.jquery.com/not-selector/或http://api.jquery.com/not/
它会是这样的:
$(':hidden').not('__RequestVerificationToken').val('');
这样做,您将获得除防伪字段之外的所有隐藏字段。
关于javascript - 使用jquery隐藏html元素后RequestVerificationToken值为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21125465/