title: MVC 3 AJAX and [ValidateAntiForgeryToken]
body: <p>I <a href="https://stackoverflow.com/questions/7264904/how-are-people-handling-ajax-posts-to-actionmethods-using-validateantiforgerytok">previously asked a question regarding this</a>, got an <a href="https://stackoverflow.com/questions/7264904/how-are-people-handling-ajax-posts-to-actionmethods-using-validateantiforgerytok/7264919#7264919">interesting answer</a> which got me on my way to, well asking more questions. So here is the next question in my journey to figure out the inner workings of AJAX posts and the rather annoying <code>ValidateAntiForgeryTokenAttribute</code>.</p>
  
  <p>I have a _layout.cshtml, this is where all of the script goodies are located for now. I have a login page that render three partials, one for OpenID logins, which is just a normal <code>@using(Html.BeginForm()) {}</code>, one for local login, and the other is for basic registration. The login partial and register partial both use ViewModels and <code>Ajax.BeginForm</code> </p>
  
  <p>Please note that I am using <code>@using Ajax.BeginForm</code> and grabbing the data-ajax-update attr to update the element on success</p>
  
  <p>Script in _layout.cshtml:</p>
  
  <pre><code>$(document).ready(function () {
      $('input[type=submit]').live("click", function (event) {
          event.preventDefault();
          var _allFormData = $(this).parents().find('form');
          var _currentForm = $(this).closest('form');
          var _updateElement = $(_currentForm).attr("data-ajax-update");
  
          $.ajax({
              type: "POST",
              url: $(_currentForm).attr('action'),
              data: $(_allFormData).serialize(),
              success: function (data) {
                  $(_updateElement).html(data);
              }
          });
  
          return true;
      });
  });
  </code></pre>
  
  <p>Form Element in _layout.cshtml</p>
  
  <pre><code>&lt;form id="__AjaxAntiForgeryForm" action="#" method="post"&gt;
      &lt;@Html.AntiForgeryToken()&gt;
  &lt;/form&gt;  
  </code></pre>
  
  <p>Action Method in Controller:</p>
  
  <pre><code>public ActionResult RegisterMember(
      RegisterMemberViewModel registerMemberViewModel)
  {
      // Process some stuff
      return PartialView("_Register");
  }
  </code></pre>
  
  <p>Why is this working, magically the <code>AntiForgeryToken</code> is getting included in all my posts. I am not grabbing it and appending it, I am not doing anything with it really it is just there. Can someone please shed some light on why this works. I don't like accidental solutions, they usually break later on.</p>