I have a ASP.NET MVC 4 form where there are checkboxes to show and hide some HTML elements. On visiting the form page, the RequestVerificationToken value is created as a hidden field correctly. The certain HTML elements are by default hidden.
I then tick a checkbox to show some HTML elements after I untick the checkbox (which hides those HTML elements) the RequestVerificationToken value disappears.
So when I submit the form by clicking create button, the following error appears:
The required anti-forgery form field "__RequestVerificationToken" is not present
If I do not untick the checkbox back, the value for RequestVerificationToken is present and form is submitted successfully.
The HTML elements are shown hidden using jQuery/javascript.
Why is this happening? How can I solve this issue? Researching the error online only suggests adding the attributes as below.
I have already added the attributes in the Create action method, but not the GET method:
// POST: /Document/Create
[HttpPost]
[ValidateAntiForgeryToken]
...
In the Create form page I also added:
@using (Html.BeginForm())
{
@Html.AntiForgeryToken()
...
Here is the Javascript to show and hide elements:
$('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);
}
}
});