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

Grid Master Detail

Hello 

I am trying to do a master detail grid with crud using odata v 4 and i can't do it 

So please if there is example for a scenario like that share it that would be helpful 

Thanks 

6 Replies

FS Farveen Sulthana Thameeztheen Basha Syncfusion Team May 29, 2017 04:41 PM UTC

Hi Zawar, 

According to your requirement, instead of reloading the data, we have retrived the deleted data using custom Adaptor.  In this sample we have used custom adaptor in “load” event and by extending the adaptor we have retrieved the deleted data Please refer to the code example  

<button id="btn" onclick="Save()">Click to save changes</button>  
<div id="Grid"></div>  
<script type="text/javascript">  
    $(function () {  
        var data =  @(Html.Raw(Json.Encode(@Request.RequestContext.HttpContext.Session["data"])));  
        $("#Grid").ejGrid({  
            dataSource: ej.DataManager({  
                json: data,  
                adaptor: new ej.remoteSaveAdaptor(),  
                batchUrl:"/Home/BatchUpdate"  
            }),  
            allowPaging:true,  
            actionFailure: "Failure",  
...  
            columns: [  
...  
            ],  
            load:"load",  
        });  
    });  
</script>  
  
<script type="text/javascript">  
    function load(args) {  
        this.model.dataSource.adaptor = new customAdaptor();  
    }  
  
    function Failure(args){  
         alert("delete failed. Please press the cancel icon to retrieve the deleted record");  
  
    }  
    var customAdaptor = new ej.remoteSaveAdaptor().extend({  
         
        batchRequest: function (dm, changes, e) {  
            var obj = []  
            obj.push(changes);  
            var res = {  
                changed: changes.changed,  
                added: changes.added,  
                deleted: changes.deleted,  
                action: "batch",  
                table: e.url,  
                key: e.key  
            };  
            return {  
                type: "POST",  
                url: dm.dataSource.batchUrl || dm.dataSource.crudUrl || dm.dataSource.url,  
                contentType: "application/json; charset=utf-8",  
                dataType: "json",  
                ejPvtData: obj,  
                data: JSON.stringify(res)  
            };  
        },  
        processResponse: function (data, ds, query, xhr, request, changes) {  
            var i;  
            var pvt = request && request.ejPvtData;  
            if(request != undefined){  
                for (i = 0; i < changes.added.length; i++)  
                    ej.JsonAdaptor.prototype.insert(ds, changes.added[i]);  
                for (i = 0; i < changes.changed.length; i++)  
                      
                    ej.JsonAdaptor.prototype.update(ds, "OrderID", changes.changed[i]);  
                for (i = 0; i < changes.deleted.length; i++)  
                    ej.JsonAdaptor.prototype.remove(ds, "OrderID", changes.deleted[i]);  
            } // updated the data after modification in grid  
            return this.base.processResponse.apply(this, [data, ds, query, xhr, request, changes]);  
        }  
  
    });  
  
    function Save(){  
        var grid = $("#Grid").ejGrid("instance");  
        grid.batchSave();  
    }  
  
</script>  
 [HomeController.cs]  
        public ActionResult BatchUpdate(List<EditableOrder> added,List<EditableOrder> changed, List<EditableOrder> deleted)  
        {  
                ...  
                
                if (deleted != null)  
                {  
                     
                        throw new Exception("TEST"); //making to fail the post when deleting action takes place  
                }  
                
...  
             
        }  

Please refer to the attached sample:- 


From the above code example by extending the adaptor we have retrieved the deleted data if deletion gets failed in server side.  
 
Note:  If we press the cancel icon after the post gets fails the deleted data will be retrieved from deletion.  
 
Refer the documentation link.  

 
Please let us know if you need further assistance.  

Regards, 

Farveen sulthana T 



FS Farveen Sulthana Thameeztheen Basha Syncfusion Team May 29, 2017 04:47 PM UTC

Hi Osama, 
Please ignore the previous update. 
Thanks for contacting syncfusion support. 

We have created sample according to your requirement which can be downloaded from the below location 
 

In this sample we have performed crudOperations with Odata V4 Adaptor on masterDetail. Please refer to the code example:- 

Clientside:- 
@(Html.EJ().Grid<object>("Editing") 
          .Datasource(ds => { ds.URL("/odata").Adaptor(AdaptorType.ODataV4Adaptor); }) 
          .EditSettings(edit => { edit.AllowAdding().AllowDeleting().AllowEditing(); }) 
            .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); 
                }); 
            }) 
            .Query("new ej.Query().from('Orders')") 
           .SelectedRowIndex(0)       
           .AllowPaging() 
           .Columns(col => 
           { 
            col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width(50).Add(); 
            col.Field("EmployeeID").HeaderText("Employee ID").Width(50).Add(); 
            col.Field("ShipCity").HeaderText("ShipCity").Width(50).Add(); 
 
        }) 
             .ClientSideEvents(eve => { eve.RowSelected("rowSelected"); }) 
) 
 
@(Html.EJ().Grid<object>("DetailGrid") 
        .Datasource((IEnumerable<object>)ViewBag.datasource2) 
        .AllowPaging(false) 
        .IsResponsive() 
        .Columns(col => 
        { 
            col.Field("EmployeeID").HeaderText("Employee ID").TextAlign(TextAlign.Right).Width(125).Add(); 
             
    }) 
) 
 
<script type="text/javascript"> 
    $(function () { 
        window.rowSelected = function (args) { 
            var employeeID = args.data.EmployeeID; 
            var data =   @(Html.Raw(Json.Encode(ViewBag.dataSource2))); 
            var detaildata = ej.DataManager(data).executeLocal(ej.Query().where("EmployeeID", ej.FilterOperators.equal, employeeID, false).take(10)); 
            var gridObj = $("#DetailGrid").ejGrid("instance"); 
            gridObj.dataSource(ej.DataManager(detaildata.slice(0, 5))); 
        } 
    }); 
</script> 

Serverside crud operations:- 
   public class OrdersController : ODataController 
    {     
      NORTHWNDEntities db = new NORTHWNDEntities(); 
        [EnableQuery] 
        public IQueryable<Order> Get() 
        { 
            return db.Orders; 
        } 
        // PUT odata/Orders(5) 
        public async Task<Order> Put(int key, Order order) //Edit operation in database 
        { 
             
           var entity =  await db.Orders.FindAsync(order.OrderID); 
           db.Entry(entity).CurrentValues.SetValues(order); 
            await db.SaveChangesAsync(); 
            return order; 
        } 
        //// POST odata/Orders 
        public async Task<Order> Post(Order order) //Add Operation in database 
        { 
             
            db.Orders.Add(order); 
            await db.SaveChangesAsync(); 
            return order; 
        } 
 
 
        //// DELETE odata/Orders(5) 
        public async Task<IHttpActionResult> Delete([FromODataUri] int key) 
        { 
             
            var od = await db.Orders.FindAsync(key); 
            if (od == null) 
            { 
                return NotFound(); 
            } 
 
            db.Orders.Remove(od); 
            await db.SaveChangesAsync(); 
            return StatusCode(HttpStatusCode.NoContent); 
        } 
    } 


Please get back to us if you need any further assistance. 

Regards, 

Farveen sulthana T 



OG osama gamal May 29, 2017 07:39 PM UTC

Hello  Farveen 

Thanks For Trying to help me 

Still the detail grid data source is loaded from the Controller, i need to make the detail grid also use odata v4


SS Seeni Sakthi Kumar Seeni Raj Syncfusion Team May 30, 2017 11:15 AM UTC

Hi Osama,  
 
We have achieved your requirement “To bind OData to the Details Grid” using the setmodel option. In the RowSelected event of the Master Grid, update the Details Grid’s dataSource and query using the setmodel option. Refer to the following code example.   
 
@(Html.EJ().Grid<object>("Editing") 
                .Datasource(ds => { ds.URL("/odata/Employees").Adaptor(AdaptorType.ODataV4Adaptor); }) 
              . . .  
                    . .  
           .SelectedRowIndex(0) 
        .AllowPaging() 
             .ClientSideEvents(eve => { eve.RowSelected("rowSelected"); }) 
) 
 
@(Html.EJ().Grid<object>("DetailGrid") 
            . ..  
              . . .  
        .Columns(col => 
        { 
            col.Field("EmployeeID").AllowEditing(false).HeaderText("Employee ID").Add(); 
            col.Field("OrderID").HeaderText("OrderID").IsPrimaryKey(true).Add(); 
            col.Field("Freight").HeaderText("Freight").Add(); 
        }) 
) 
 
<script type="text/javascript"> 
 
    function rowSelected(args) { 
        var employeeID = args.data.EmployeeID; 
        var gridObj = $("#DetailGrid").ejGrid("instance"); 
        gridObj.option({ 
            query: ej.Query().where("EmployeeID", ej.FilterOperators.equal, employeeID, false), 
            dataSource: ej.DataManager({ 
                url: "/odata/Orders", 
                adaptor: new ej.ODataV4Adaptor() 
            }), 
            actionBegin: function (args) { 
                if (args.requestType == "refresh") 
                    this.model.columns[0].defaultValue = employeeID; 
            } 
        }) 
    } 
</script> 
 
To update the Parent Grid’s foreignkey value in the EditForm, we have used the defaultValue property of the Grid columns and it has been updated in the actionBegin event of the DetailGrid. 
 
We have prepared a sample that can be downloaded from the following location.  
 
 
 
Regards,  
Seeni Sakthi Kumar S. 



OG osama gamal May 31, 2017 12:30 AM UTC

Thanks that was exactly what i was looking for :)


SS Seeni Sakthi Kumar Seeni Raj Syncfusion Team May 31, 2017 04:06 AM UTC

Hi Osama,  
 
Thanks for the update. We are happy to hear that your requirement has been achieved and you are good to go. Please get back to us, if you require further assistance on this.  
 
Regards,  
Seeni Sakthi Kumar S. 


Loader.
Up arrow icon