MVC 3 AJAX and [ValidateAntiForgeryToken]

纵然是瞬间 提交于 2019-12-13 16:24:00

问题


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.


回答1:


The @Html.AntiForgeryToken() creates an <input type='hidden' name='__RequestVerificationToken'/> or something similar inside your form. And if I understand correctly this: var _allFormData = $(this).parents().find('form'); in combination with this:data: $(_allFormData).serialize() post all your form data to the server, including the inputfield __RequestVerificationToken which MVC probably looks for,



来源:https://stackoverflow.com/questions/7270387/mvc-3-ajax-and-validateantiforgerytoken

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!