Search code examples
asp.net-mvcjqgrid

Use ValidateAntiForgeryToken with JQGrid in asp.net MVC?


In a hybrid asp.net web forms/mvc 5.2.6 application, using JQuery.jqGrid v4.4.4, I'm struggling to discover a way to use the ValidateAntiForgeryToken attribute on the Controller method that jqGrid posts to when fetching its data.

The grid is read-only. The "datatype" is "json" and the "mtype" is "POST". I've tried simply appending the value of the __RequestVerificationToken hidden input to the data that gets posted back to the Controller, but that does not work; the site simply throws a missing antiforgery token exception.

I notice that when one wants to make an $.ajax post of json data to a Controller method one can pass the __RequestVerificationToken in the "headers" parameter. While the jqGrid makes an $.ajax call behind the scenes, unfortunately it does not have a headers parameter.

I've found examples on SO where one can pass the token via the editData parameter (such as this: JQGrid able to pass ValidateAntiForgeryToken through the main CRUD controls?), but my grid is read-only, and in any case I want to enforce the token when the user enters search criteria and then clicks a button to fill the grid.

Is there any way to use the ValidateAntiForgeryToken when filling a jqgrid?


Solution

  • You can include postData parameter with __RequestVerificationToken property defined as the following function:

    postData: {
        __RequestVerificationToken: function () {
            return jQuery("input[name=__RequestVerificationToken]").val();
        }
    }
    

    It will add __RequestVerificationToken parameter to all request sent to the server during filling the grid.