I previously asked a question regarding this, got an interesting answer 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 ValidateAntiForgeryTokenAttribute
.
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 @using(Html.BeginForm()) {}
, one for local login, and the other is for basic registration. The login partial and register partial both use ViewModels and Ajax.BeginForm
Please note that I am using @using Ajax.BeginForm
and grabbing the data-ajax-update attr to update the element on success
Script in _layout.cshtml:
$(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;
});
});
Form Element in _layout.cshtml
<form id="__AjaxAntiForgeryForm" action="#" method="post">
<@Html.AntiForgeryToken()>
</form>
Action Method in Controller:
public ActionResult RegisterMember(
RegisterMemberViewModel registerMemberViewModel)
{
// Process some stuff
return PartialView("_Register");
}
Why is this working, magically the AntiForgeryToken
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.