We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

ValidateAntiForgeryToken is not working in CRUD Model method and cannot able to implement in GRID Inline template

     
 Hi,
           ValidateAntiForgeryToken is not working in crudmodel method using inline template grid create/update,
please guide me to overcome this issues. i have mentioned sample methods which we use..

        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult _crudData([FromBody]CRUDModel<Object> inDataRecord, String src)
        {
            bool goNextStep = true;  //used to minmize if nesting.
            bool actionOK = false;
            string msg = "Data update failed.";
            object dataUpdated = null;
            if (src == null || src == "")
            {
                msg = "Invalid entity reference.  " + msg;
                goNextStep = false;
            }

            //Check model state before processing.
            if (!ModelState.IsValid)
            {
                //Pass the error messaged to Grid display
                msg = msg + ".  Invaid data : " + string.Join(" | ", ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage));
                //viewModel._msg = _localizer[ResourceConstants.SaveFailedWithErrors] + "\r" + errorMessage
                goNextStep = false;
            }

            if (goNextStep)     //Source Entity is available
            {
                try
                {
                   if (inDataRecord.Action == SyncFusionConstants.update || inDataRecord.Action == SyncFusionConstants.insert)
                    {
                        dataUpdated = _ebmsBO._saveData(inDataRecord, src);
                        actionOK = true;  //No switch failed. Warning : If invalud action string passed then it will assume success !!!
                    }
                    else if (inDataRecord.Action == SyncFusionConstants.delete)
                    {
                        dataUpdated = _ebmsBO._deleteData(inDataRecord, src);
                        actionOK = true;  //No switch failed. Warning : If invalud action string passed then it will assume success !!!
                    }
                }
                catch (Exception e)
                {
                    msg = msg + ". " + e.Message.ToString();
                }
            }
            //Return BadResponse or updated records
            ViewBag.Success = actionOK;
            ViewBag.msg = msg;
            if (actionOK) { return Json(inDataRecord.Value); } else { return BadRequest(inDataRecord.Value); }
        }

This method is not firing after use ValidateAntiForgeryToken if i remove ValidateAntiForgeryToken than its works fine while submit save or udpate..
please guide me to overcome with ValidateAntiForgeryToken..

Thanks,
Ramlith

3 Replies

JK Jayaprakash Kamaraj Syncfusion Team February 14, 2017 04:42 PM UTC

Hi Ramlith, 

Thank you for contacting Syncfusion support. 

We have created a sample based on your requirement using AntiForgeryToken. While using AntiForgeryToken to editing we need to use AntiForgeryToken() html method in edit form. Because Antiforgery token validate the inside form element, 



@{Html.EJ().Grid<Object>("FlatGrid") 
                                    .Datasource(ds => ds.URL("/Home/DataSource").CrudURL("/Home/CrudUpdate").RemoveURL("/Home/Remove").Adaptor(AdaptorType.UrlAdaptor)) 
                            .AllowPaging() 
                            .ClientSideEvents(eve => { eve.ActionComplete("complete").Load("load"); }) 
                            .EditSettings(edit => { edit.AllowAdding().AllowDeleting().AllowEditing().EditMode(EditMode.InlineFormTemplate).InlineFormTemplateID("#template"); }) 
……… 
 
                            }).Render(); 
} 
 
<script id="template" type="text/template"> 
    @Html.AntiForgeryToken() 
    <table cellspacing="10"> 
        <tr> 
            <td style="text-align: right;"> 
                Order ID 
            </td> 
            <td style="text-align: left"> 
                 
                <input id="OrderID" name="OrderID" value="{{: OrderID}}" disabled="disabled" class="e-field e-disable e-ejinputtext valid" style="text-align: right; width: 116px; height: 28px" /> 
            </td> 
..  
    </table> 
     
     
</script> 
<script type="text/javascript"> 
    var dmAdaptorUpdate = function (keyField, value, tableName) { 
        var res = this.adaptor.update(this, keyField, value, tableName); 
        return $.ajax($.extend({ 
            beforeSend: ej.proxy(this._beforeSend, this) 
        }, res)); 
    } 
    var dmAdaptorInsert = function (data, tableName) { 
        var res = this.adaptor.insert(this, data, tableName); 
        var deffer = $.Deferred(); 
        $.ajax($.extend({ 
            beforeSend: ej.proxy(this._beforeSend, this), 
            success: ej.proxy(function (record, status, xhr, request) { 
                record = function () { 
                    if (data.d) 
                        data = data.d; 
                    return data; 
                }; 
                deffer.resolveWith(this, [{ record: record, dataManager: this }]); 
            }, this), 
            error: function (e) { 
                deffer.rejectWith(this, [{ error: e, dataManager: this }]); 
            } 
        }, res)); 
 
        return deffer.promise(); 
    } 
    var adaptor = new ej.UrlAdaptor().extend({ 
        update: function (dm, keyField, value, tableName) { 
            var token = $('input[type=hidden][name=__RequestVerificationToken]', document).val(); 
            delete value['__RequestVerificationToken']; 
            return { 
                headers: { 
          
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 
                }, 
                type: "POST", 
                dataType:"json", 
                url: dm.dataSource.updateUrl || dm.dataSource.crudUrl || dm.dataSource.url, 
                data: { 
                    __RequestVerificationToken: token, 
                    value: value, 
                    action: "update", 
                }, 
                
            }; 
        }, 
        insert: function (dm, data, tableName) { 
            var token = $('input[type=hidden][name=__RequestVerificationToken]', document).val(); 
            delete data['__RequestVerificationToken']; 
            return { 
                headers: {                   
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', 
                }, 
                type: "POST", 
                url: dm.dataSource.insertUrl || dm.dataSource.crudUrl || dm.dataSource.url, 
                data: { 
                    __RequestVerificationToken: token, 
                    value: data, 
                    action:"insert" 
                } 
            }; 
        } 
    }) 
 
    function load(args) { 
        this.model.dataSource.adaptor = new adaptor(); 
        this.model.dataSource.update = dmAdaptorUpdate; 
        this.model.dataSource.insert = dmAdaptorInsert; 
    } 
  </script> 
 
[HttpPost]  
  [AllowAnonymous] 
[ValidateAntiForgeryToken] 
         
        public ActionResult CrudUpdate(Orders value, string action) 
        { 
           // do your actions here 
            return Json(new { order }); 
        } 
 
        public ActionResult Remove([FromBody]CRUDModel<Orders> myobject) 
        { 
// do your actions here 
 
            return Json(new { order }); 
        } 

In the above sample we have extend the adaptor to include the AntiForgeryToken key before send post to server side.

Refer to the online help documentation for custom adaptor for adaptor extend,

Document: http://help.syncfusion.com/js/datamanager/data-adaptors#custom-adaptor 
 
Regards, 
 
Jayaprakash K. 



LE Leon April 15, 2017 07:07 PM UTC

I was very happy about using the grid control, because it makes my development fast and clean. So far I like everything about the grid control. But if to make it more secure by trying to use ValidateAntiForgeryToken, I have to write all my grids in java script code to include this functionality, I am a little disappointed. Inline editing is very convenient and I can use it a lot across my application, But I would like to have some level of confidence in the validity of the posts. Having said all this my question is: Is there a way to implement ValidateAntiForgeryToken() keeping the grid the way I have it today in my RAZOR/CSHTML () ? If not do you see that as a future enhancement? or what other alternatives can I use to mimic the ValidateAntiForgeryToken() functionality?Thanks in advance


JK Jayaprakash Kamaraj Syncfusion Team April 17, 2017 03:56 PM UTC

Hi Juan, 
We have already logged a feature request “Antiforgery support in Datamanager” and it can be implemented in any of our upcoming release. 
 
As of now, we suggest you to include all JavaScript codes(custom Adaptor) in to separate js file and refer that js file into Layout page and then we can use it(custom Adaptor) all the Grid. 
Regards, 
 
Jayaprakash K. 


Loader.
Live Chat Icon For mobile
Up arrow icon