Articles in this section
Category / Section

How to add anti forgery token in JS Grid CRUD requests headers?

1 min read

This Knowledge base showcase the example to add anti forgery token in Grid CRUD requests headers through JavaScript Grid

Solution

By extending the Adaptor CRUD actions, we can add the anti-forgery token in Grid CRUD requests headers. Here we have used removeSaveAdaptor.

Render the grid control.

HTML

<div id="FlatGrid"></div>

 

JS

<input type="hidden" name="_ejRequestVerifyToken" value="f2cd20a3-5ae1-4e19-be61-d409191be3b1">
<script>
    var data = @Html.Raw(Json.Encode(ViewBag.datasource));
    var DataManager = ej.DataManager({ json: data, adaptor: new ej.remoteSaveAdaptor(), updateUrl: "/Grid/Update", insertUrl: "/Grid/Insert", removeUrl:"/Grid/Remove" });
    $(function () {
        $("#FlatGrid").ejGrid({
            dataSource: DataManager,
            allowPaging: true,
            load:"load",
            toolbarSettings: {showToolbar: true, toolbarItems: ["add", "edit", "delete", "update", "cancel"]},
            editSettings: {allowEditing: true, allowAdding: true, allowDeleting: true},
            columns: [
                {field: "OrderID", headerText: "Order ID", isPrimaryKey: true},
                {field: "CustomerID", headerText: "Customer ID"},
                {field: "ShipCity", headerText: "Ship City", editType:"dropdown"}
            ]
        });
    });
</script>

 

MVC

<input type="hidden" name="_ejRequestVerifyToken" value="f2cd20a3-5ae1-4e19-be61-d409191be3b1">
@(Html.EJ().Grid<object>("FlatGrid")
           .Datasource(ds => ds.Json((IEnumerable<object>)ViewBag.datasource).UpdateURL("/Grid/Update").InsertURL("/Grid/Insert").RemoveURL("/Grid/Remove").Adaptor(AdaptorType.RemoteSaveAdaptor))
           .AllowPaging()
           .EditSettings(edit => edit.AllowAdding().AllowDeleting().AllowEditing().EditMode(EditMode.Normal))
           .ToolbarSettings(toolbar =>
           {
               toolbar.ShowToolbar().ToolbarItems(items =>
               {
                   items.AddTool(ToolBarItems.Add);
                   items.AddTool(ToolBarItems.Edit);
                   items.AddTool(ToolBarItems.Delete);
                   items.AddTool(ToolBarItems.Update);
                   items.AddTool(ToolBarItems.Cancel);
               });
           })
           .ClientSideEvents(eve => { eve.Load("load"); })
           .Columns(col =>
                {
                    col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Add();
                    col.Field("CustomerID").HeaderText("Customer ID").Add();
                    col.Field("ShipCity").HeaderText("Ship City").EditType(EditingType.DropdownEdit).Add();
                })
)

 

CS

 
public class GridController : Controller
    {
        public ActionResult GridFeatures()
        {
            var data = OrderRepository.GetAllRecords();
            ViewBag.datasource = data;
            return View();
        }
        public ActionResult Update(EditableOrder value)
        {
            OrderRepository.Update(value);
            var data = OrderRepository.GetAllRecords();
            return Json(data, JsonRequestBehavior.AllowGet);
        }
        public ActionResult Insert(EditableOrder value)
        {
            OrderRepository.Add(value);
            var data = OrderRepository.GetAllRecords();
            return Json(data, JsonRequestBehavior.AllowGet);
        }
        public ActionResult Remove(int key)
        {
            OrderRepository.Delete(key);
            var data = OrderRepository.GetAllRecords();
            return Json(data, JsonRequestBehavior.AllowGet);
        }
    }

 

ASP

<input type="hidden" name="_ejRequestVerifyToken" value="f2cd20a3-5ae1-4e19-be61-d409191be3b1">
    <div>
        <ej:DataManager ID="FlatData" runat="server" Adaptor="remoteSaveAdaptor" InsertURL="Default.aspx/Insert" RemoveURL="Default.aspx/Remove" UpdateURL="Default.aspx/Update" />
        <ej:Grid ID="FlatGrid" runat="server" AllowPaging="True" DataManagerID="FlatData">
            <EditSettings AllowEditing="True" AllowAdding="True" AllowDeleting="True" EditMode="Normal"></EditSettings>
            <ToolbarSettings ShowToolbar="True" ToolbarItems="add,edit,delete,update,cancel"></ToolbarSettings>
            <Columns>
                <ej:Column Field="OrderID" IsPrimaryKey="true" HeaderText="Order ID" />
                <ej:Column Field="CustomerID" HeaderText="Customer ID" />
                <ej:Column Field="ShipCity" HeaderText="Ship City" EditType="DropdownEdit"/>
            </Columns>
            <ClientSideEvents Load="load" />
        </ej:Grid>
    </div>

 

CS

        protected void Page_Load(object sender, EventArgs e)
        {
            this.FlatData.Json = OrderRepository.GetAllRecords();
            this.FlatGrid.DataBind();
 
        }
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static object Update(EditableOrder value)
        {
            OrderRepository.Update(value);
            return value;
        }
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static object Insert(EditableOrder value)
        {
            OrderRepository.Add(value);
            return value;
        }
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static void Remove(int key)
        {
            OrderRepository.Delete(key);
        }

 

 

 

.Net core

<input type="hidden" name="_ejRequestVerifyToken" value="f2cd20a3-5ae1-4e19-be61-d409191be3b1">
<div id="ControlRegion">
    <ej-grid id="FlatGrid" allow-paging="true" load="load">
        <e-datamanager json="(IEnumerable<object>)ViewBag.datasource" update-url="Update" insert-url="Insert" remove-url="Delete" adaptor="remoteSaveAdaptor" />
        <e-edit-settings allow-adding="true" allow-editing="true" allow-deleting="true" edit-mode="@(EditMode.Normal)"></e-edit-settings>
        <e-toolbar-settings show-toolbar="true" toolbar-items='@new List<string> {"add", "edit","delete","update","cancel"}'></e-toolbar-settings>
        <e-columns>
            <e-column field="OrderID" header-text="Order ID" is-primary-key="true"></e-column>
            <e-column field="CustomerID" header-text="Customer ID"></e-column>
            <e-column field="ShipCity" header-text="Ship City" edit-type="DropdownEdit"></e-column>
        </e-columns>
    </ej-grid>
</div>
 

 

CS

public partial class GridController : Controller
    {
        public static List<OrderDetails> order = new List<OrderDetails>();
 
        public ActionResult GridFeatures()
        {
            if (order.Count() == 0)
                BindDataSource();
            ViewBag.datasource = order;
            return View();
        }
        public ActionResult Update([FromBody]CRUDModel<OrderDetails> myObject)
        {
            var ord = myObject.Value;
            OrderDetails val = order.Where(or => or.OrderID == ord.OrderID).FirstOrDefault();
            val.OrderID = ord.OrderID;
            val.EmployeeID = ord.EmployeeID;
            val.CustomerID = ord.CustomerID;
            val.Freight = ord.Freight;
            val.ShipCity = ord.ShipCity;
            return Json(myObject.Value);
        }
        public ActionResult Insert([FromBody]CRUDModel<OrderDetails> value)
        {
            order.Insert(order.Count, value.Value);
            return Json(order);
        }
        public ActionResult Delete([FromBody]CRUDModel<OrderDetails> value)
        {
            order.Remove(order.Where(or => or.OrderID == int.Parse(value.Key.ToString())).FirstOrDefault());
            return Json(value);
        }
    }
}

 

Angular

Index file

Define the token value in the index file of the application

<input type="hidden" name="_ejRequestVerifyToken" value="f2cd20a3-5ae1-4e19-be61-d409191be3b1">

 

Html file

<ej-grid #grid [dataSource]="gridData" allowPaging="true" (load)="load($event)" [toolbarSettings]="toolbarItems" [editSettings]="editSettings">
    <e-columns>
        <e-column field="OrderID" headerText="Order ID" [isPrimaryKey]="true"></e-column>
        <e-column field="CustomerID" headerText="Customer ID"></e-column>
        <e-column field="ShipCity" headerText="Ship City" editType="dropdownedit"></e-column>
    </e-columns>
</ej-grid>

 

Ts File

import { Component, OnInit, Input, ElementRef, ViewChild } from '@angular/core';
import { EJComponents } from "ej-angular2/src/ej/core";
import { data } from "./data";
@Component({
    selector: 'ej-app',
    templateUrl: 'src/grid/grid.component.html',
})
export class GridComponent {
    public gridData: any;
    public editSettings;
    public toolbarItems;
    @ViewChild('grid') Grid: EJComponents<any, any>;
    constructor() {
        this.gridData = new ej.DataManager({
            json: data,
            updateUrl: "/Grid/Update", insertUrl: "/Grid/Insert",
            removeUrl: "/Grid/Remove",
            adaptor: new ej.remoteSaveAdaptor()
        });
        this.editSettings = { allowEditing: true, allowAdding: true, allowDeleting: true };
        this.toolbarItems = { showToolbar: true, toolbarItems: ["add", "edit", "delete", "update", "cancel"] };
    }
}
 
 

 

Extend each CRUD action of the remoteSaveAdaptor and add the antiforgery token value in the headers of the result. Later, the extended adaptor has been assigned to the Grid’s dataSource in the load event.

    var tokenValue = $("input[name=_ejRequestVerifyToken]").val();
    var adaptor = new ej.remoteSaveAdaptor().extend({
        update: function (dm, keyField, value, tableName) {
            var result = this.base.update.apply(this, [dm, keyField, value, tableName]);
            ej.createObject("headers", { "X-CSRF-Token": tokenValue }, result)
            return result;
        },
        insert: function (dm, data, value, tableName) {
            var result = this.base.insert.apply(this, [dm, data, value, tableName]);
            ej.createObject("headers", { "X-CSRF-Token": tokenValue }, result)
            return result;
        },
        remove: function (dm, keyField, value, tableName, query) {
            var result = this.base.remove.apply(this, [dm, keyField, value, tableName, query]);
            ej.createObject("headers", { "X-CSRF-Token": tokenValue }, result)
            return result;
        }
    })
    function load(args) {
        this.model.dataSource.adaptor = new adaptor();
    }

 

 

import { Component, OnInit, Input, ElementRef, ViewChild } from '@angular/core';
import { EJComponents } from "ej-angular2/src/ej/core";
import { data } from "./data";
@Component({
    selector: 'ej-app',
    templateUrl: 'src/grid/grid.component.html',
})
export class GridComponent {
    public gridData: any;
    public adaptor: any;
    @ViewChild('grid') Grid: EJComponents<any, any>;
    constructor() {
        this.adaptor = new ej.remoteSaveAdaptor().extend({
            update: function (dm, keyField, value, tableName) {
                var tokenValue = $("input[name=_ejRequestVerifyToken]").val();
                var result = this.base.update.apply(this, [dm, keyField, value, tableName]);
                ej.createObject("headers", { "X-CSRF-Token": tokenValue }, result)
                return result;
            },
            insert: function (dm, data, value, tableName) {
                var tokenValue = $("input[name=_ejRequestVerifyToken]").val();
                var result = this.base.insert.apply(this, [dm, data, value, tableName]);
                ej.createObject("headers", { "X-CSRF-Token": tokenValue }, result)
                return result;
            },
            remove: function (dm, keyField, value, tableName, query) {
                var tokenValue = $("input[name=_ejRequestVerifyToken]").val();
                var result = this.base.remove.apply(this, [dm, keyField, value, tableName, query]);
                ej.createObject("headers", { "X-CSRF-Token": tokenValue }, result)
                return result;
            }
        });
    }
    load(e) {
        this.gridData.adaptor = new this.adaptor;
    }
}
 
 

 

 

Figure 1 Insert Action

Figure 2 Update Action

Figure 3 Remove Action

 

Conclusion

I hope you enjoyed learning about how to add anti forgery token in JS Grid CRUD request headers.

You can refer to our JavaScript Grid feature tour page to learn about its other groundbreaking feature representations and documentation, and how to quickly get started for configuration specifications. You can also explore our JavaScript Grid example to understand how to create and manipulate data.

For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our other controls.

If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forumsDirect-Trac, or feedback portal. We are always happy to assist you!

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments (0)
Please sign in to leave a comment
Access denied
Access denied