Share via


How can i supply a antiforgerytoken when posting JSON data using $.ajax ?

Question

Tuesday, May 25, 2010 11:47 AM

I am using the code as below of this post:

First i will an fill array variable with the correct values for the controller action.
Using the code below i think it should be very straigtforward by just adding the following line to the javascript:

***data["__RequestVerificationToken"] = $('[name=__RequestVerificationToken]').val();


The <%= Html.AntiForgeryToken() %> is at his right place and the action has a [ValidateAntiForgeryToken]

But my controller action keeps saying: "Invalid forgery token" 

 

What am i doing wrong here?

 

====================CODE=======================

    data["fiscalyear"] = fiscalyear;
    data["subgeography"] = $(list).parent().find('input[name=subGeography]').val();
    data["territories"] = new Array();

***    $(items).each(function() {
        data["territories"].push($(this).find('input[name=territory]').val());
    });***

***        if (url != null) {
            $.ajax(
            {
                dataType: 'JSON',
                contentType: 'application/json; charset=utf-8',
                url: url,
                type: 'POST',
                context: document.body,
                data: JSON.stringify(data),
                success: function() { refresh(); }
            });
        }***

All replies (2)

Tuesday, May 25, 2010 4:41 PM âś…Answered

You probably allready saw this, but just for in case:


Tuesday, May 25, 2010 2:03 PM

The problem is that you send everything as JSON, even the antiforgery token. I don't think that ASP.NET will parse the antiforgery token from the JSON structure. Below is a sample I created and which worked for me:

<%@ Page Language="C#" Inherits="System.Web.Mvc.ViewPage<dynamic>" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>Index</title>
    <script src="/Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script src="/Scripts/json2.js" type="text/javascript"></script>
</head>
<body>
    <%: Html.AntiForgeryToken() %>
    <div>
        <div>
            <span>Message: </span>
            <span id="message"></span>
        </div>
        <div>
            <span>Text:</span>
            <input type="text" id="text" name="text" />
        </div>
        <div>
            <input type="button" value="Do Ajax Request" id="ajaxButton" />
        </div>
    </div>
    <script type="text/javascript" language="javascript">
        $(document).ready(function () {
            $('#ajaxButton').click(function () {
                var postData = {
                    __RequestVerificationToken: $('[name= "__RequestVerificationToken"]').val(),
                    text: $('#text').val()
                };
                $.ajax({
                    url: '/Home/GetMessage',
                    type: 'POST',
                    data: postData,
                    success: function (response) { $('#message').text(response); }
                });
            });
        });
    </script>
</body>
</html>

Best of luck!

 /Robert