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.
Unfortunately, activation email could not send to your email. Please try again.

Grid not refreshing after insert

Thread ID:

Created:

Updated:

Platform:

Replies:

131493 Jul 12,2017 05:44 PM Jul 16,2017 11:38 PM ASP.NET MVC 5
loading
Tags: Grid
Cristian Calderon
Asked On July 12, 2017 05:44 PM

I've created a grid with editing features, works fine but when add a new item this item is not shown on the grid, only the total number is refreshed, the edit and delete functions works.

This is the code:
View:
     @(Html.EJ().Grid<object>("Grid")
                .Datasource(ds => ds.URL(Url.Action("Data"))
                    .UpdateURL(Url.Action("Edit")).InsertURL(Url.Action("Create")).RemoveURL(Url.Action("Delete"))
                    .Adaptor(AdaptorType.RemoteSaveAdaptor))
                .IsResponsive()
                .EnableResponsiveRow()
                .AllowPaging()
                .AllowSorting()
                .AllowSearching()
                .PageSettings(p => p.PageCount(5).PageSize(10))
                .EditSettings(edit =>
                {
                    edit.AllowAdding().AllowDeleting().AllowEditing().RowPosition(RowPosition.Bottom)
                        .EditMode(EditMode.InlineForm).ShowDeleteConfirmDialog();
                })
                .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);
                    });
                })
                .ContextMenuSettings(contextMenu =>
                {
                    contextMenu.EnableContextMenu();
                })
                .Columns(col =>
                {
                    col.Field("PaisId").HeaderText("Código").Width(10).IsPrimaryKey(true).EditType(EditingType.Numeric).DefaultValue(0)
                        .ValidationRules(v => v.AddRule("required", true)).Add();
                    col.Field("Nombre").HeaderText("Nombre").Width(90)
                        .ValidationRules(v => v.AddRule("required", true).AddRule("maxlength", 50)).Add();

                })
                .ClientSideEvents(eve => eve.Load("load").ActionComplete("complete").ActionBegin("begin").EndEdit("endEdit").EndAdd("endAdd"))
                )

Controller:
         // GET: Paises/Data
        [HttpPost]
        [Route("Data")]
        public ActionResult Data(Syncfusion.JavaScript.DataManager dm)
        {
            int totalRecords = 0;

            // Iniciamos la lista y contamos el total de elementos
            IQueryable<Pais> query = db.Paises;

            if (dm.Search != null)
            {
                var search = dm.Search[0].Key.ToLower(); // Pasamos la busqueda a minusculas
                query = query.Where(x => x.Nombre.ToLower().Contains(search));
            }

            string field = "PaisId"; // Orden por defecto
            string direction = "asc";

            if (dm.Sorted != null)
            {
                direction = dm.Sorted[0].Direction == "ascending" ? "asc" : "desc";
                field = dm.Sorted[0].Name;                
            }

            query = query.OrderBy($"{field} {direction}");

            totalRecords = query.Count();

            var data = query.Skip(dm.Skip).Take(dm.Take).ToList();

            return Json(new { result = data, count = totalRecords });
        }

        // POST: Paises/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see https://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "PaisId,Nombre")] Pais pais)
        {
            if (ModelState.IsValid)
            {              
                db.Paises.Add(pais);
                db.SaveChanges();
            }

            return View(pais);
        }

I attached the complete source code files. Thank You for your help.


Attachment: Sample_bc7e521c.rar

Mani Sankar Durai [Syncfusion]
Replied On July 13, 2017 08:22 AM

Hi Cristian, 

Thanks for contacting Syncfusion support. 

We have analyzed your query and we are not able to reproduce the reported issue. We have also prepared a sample that can be downloaded from the below link. 
In this sample we have performed editing operations and while adding the record it is saved in grid. Here we have used anti forgery token in URLAdaptor and performed server side CRUD operations in grid. 
Refer the code example 
  [ValidateAntiForgeryToken] 
        public ActionResult Insert(Order value) 
        { 
            db.Orders.Add(value); 
            db.SaveChanges(); 
            var data = db.Orders.ToList(); 
            
            return Json(data, JsonRequestBehavior.AllowGet); 
        } 
        public ActionResult Remove(int key) 
        { 
            Order order = db.Orders.Find(key); 
            db.Orders.Remove(order); 
            db.SaveChanges(); 
            return Json(order, JsonRequestBehavior.AllowGet);  
        } 
 
@(Html.EJ().Grid<object>("Editing") 
        .Datasource(ds => ds.URL("/Home/UrlDataSource").Adaptor(AdaptorType.UrlAdaptor).UpdateURL("/Home/Update").InsertURL("/Home/Insert").RemoveURL("/Home/Remove")) 
        .EditSettings(edit => edit.AllowAdding().AllowDeleting().AllowEditing().EditMode(EditMode.InlineFormTemplate).InlineFormTemplateID("#template")) 
        ... 
        }) 
        .AllowPaging() 
        .Columns(col => 
        { 
        }) 
  .ClientSideEvents(eve => eve.Load("load")) 
 
) 
<script type="text/template" id="template"> 
    <b>Order Details</b> 
    @Html.AntiForgeryToken() 
    ... 
</script> 
@*@Html.Partial("EditTemplate")*@ 
<script> 
... 
    var dmAdaptorInsert = function (data, tableName) { 
        var res = this.adaptor.insert(this, data, tableName); 
... 
 
    var adaptor = new ej.UrlAdaptor().extend({ 
        ... 
       
        insert: function (dm, data, tableName) { 
            var token = $('input[type=hidden][name=__RequestVerificationToken]', document).val(); 
            data['__RequestVerificationToken'] = token; 
            return { 
                type: "POST", 
                url: dm.dataSource.insertUrl || dm.dataSource.crudUrl || dm.dataSource.url, 
                data: { 
                    __RequestVerificationToken: token, 
                    value: data 
                } 
            }; 
        } 
    }) 
 
    function load(args) { 
        this.model.dataSource.adaptor = new adaptor(); 
        this.model.dataSource.update = dmAdaptorUpdate; 
        this.model.dataSource.insert = dmAdaptorInsert; 
        this.model.dataSource.remove = dmAdaptorRemove; 
    } 
</script> 

Note: We have also suspect from the query that the added record may be saved in the last page of grid due to autoincrement column. 
If you still face the issue please get back to us with the following details. 
1.       Share the screenshot/video of the issue.  
2.       Ensure whether the added record is added in the last page of grid? 
3.       Is possible please reproduce the issue in the above attached sample. 
The provided information will help us to analyze the issue and provide you the response as early as possible. 

Please let us know if you need further assistance 

Regards, 
Manisankar Durai. 



Cristian Calderon
Replied On July 13, 2017 01:27 PM

Thank you for your response, I downloaded and test your sample, but the bug persist in the sample, now I suspect that is a version bug, I don't have the same assemblies and I manually edited this to match with mine. I attached a video to show you the problem, thank you for your help.


Attachment: syncfusion_gridbug_e9f8e870.rar

Mani Sankar Durai [Syncfusion]
Replied On July 14, 2017 07:27 AM

Hi Cristian, 

We have checked the provided video and we are able to reproduce the reported issue. The cause of an issue is due to return the function instead of passing the updated record as an object in the adaptor. 
  
Refer the code example 
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;               //it is not needed since you have set the function to the record instead of passing the value. so please remove this code. 
                }; 
                deffer.resolveWith(this, [{ record: record, dataManager: this }]); 
            }, this), 
            error: function (e) { 
                deffer.rejectWith(this, [{ error: e, dataManager: this }]); 
            } 
        }, res)); 
 
        return deffer.promise(); 
    } 
 
Since from DB you have set as Identity column for the grid. So when adding it goes on auto incrementing the value. For this we suggest you to pass the value from server side after the record being added in db. 

Refer the code example 

[ValidateAntiForgeryToken] 
        public ActionResult Insert(Order value) 
        { 
           db.Orders.Add(value); 
            db.SaveChanges(); 
            var data = db.Orders.ToList(); 
           var val = data.Last(); 
            return Json(val, JsonRequestBehavior.AllowGet);   //pass the added value after the record being added in DB 
        } 

We have also prepared a sample that can be downloaded from the below link. 


Please let us know if you need further assistance. 


Regards, 
Manisankar Durai. 




Cristian Calderon
Replied On July 14, 2017 12:25 PM

Thank You, all works fine after remove the suggested lines.


Mani Sankar Durai [Syncfusion]
Replied On July 16, 2017 11:38 PM

Hi Cristian 

We are happy to hear that your problem has been solved. 

Please let us know if you need further assistance. 

Regards, 
Manisankar Durai. 


CONFIRMATION

This post will be permanently deleted. Are you sure you want to continue?

Sorry, An error occured while processing your request. Please try again later.

You are using an outdated version of Internet Explorer that may not display all features of this and other websites. Upgrade to Internet Explorer 8 or newer for a better experience.

;