1

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);
    }
}
});
Qwerty
  • 323
  • 1
  • 6
  • 33
  • The element is really hidden or it is disabled? http://stackoverflow.com/questions/1355728/values-of-disabled-inputs-will-not-be-submited – Felipe Miosso Jan 14 '14 at 22:38
  • The element I hide with the checkbox is div. The div has style="display: none" to hide and style="" to show the element. Is this not right? How can this remove the value of request token? – Qwerty Jan 14 '14 at 22:46
  • Can you show your javascript? – Jason P Jan 14 '14 at 22:49
  • Ok I added the JS, not sure how to properly add the indents in this code editting. – Qwerty Jan 14 '14 at 22:53
  • Ahhhh I got it! It is this line: jQuery(':hidden').val(''); isn't it?? I was trying to remove the value of form fields when hidden to reset them. What is the alternative? Because it is removing the RequestVerificationToken too – Qwerty Jan 14 '14 at 22:56

1 Answers1

1

Use jQuery .not(). http://api.jquery.com/not-selector/ or http://api.jquery.com/not/

It will be something like this:

$(':hidden').not('__RequestVerificationToken').val('');

Doing that you will get all the hidden fields except for the antiforgery one.

Felipe Miosso
  • 7,309
  • 6
  • 44
  • 55