Refresh Grid After Insert / Update / Delete

I have a grid 

<ejs-grid #grid allowPaging='true' allowFiltering='true' allowSorting='true'
            [dataSource]='data' [allowGrouping]='true' allowResizing='true' showColumnMenu='true'
            [editSettings]='editSettings' [toolbar]='toolbar' [showColumnChooser]='true'
            [allowExcelExport]='true' [allowPdfExport]='true' [filterSettings]='filterSettings'>
    <e-columns>
      <e-column field='id' [isPrimaryKey]='true' [isIdentity]="true" [visible]='false'></e-column>
      <e-column field='name' headerText='Name' [validationRules]='required' width='150'></e-column>
      <e-column field='ipAddress' headerText='IP Address' width='150'></e-column>
      <e-column field='gateId' editType="dropdownedit" headerText='Gate' width='150'
                [validationRules]='required' foreignKeyField="id" foreignKeyValue="name"
                [dataSource]='gateData' [edit]='ddParams'>
      </e-column>
    </e-columns>
  </ejs-grid>

Binded to 

this.data = new DataManager({
      url: this.baseUrl + 'api/Tags/GetByDataManager',
      insertUrl: this.baseUrl + 'api/Tags/InsertUpdate',
      updateUrl: this.baseUrl + 'api/Tags/InsertUpdate',
      removeUrl: this.baseUrl + 'api/Tags/Remove',
      adaptor: new UrlAdaptor
    })

as you can see it is remote data source, using edit setting 'Dialog'.

Now what I need is when it inserts / updates / deletes a row, it should be updated. The database is actually updated but only grid is not.

My aspnet current code at server is below. I think I am missing a return type or something like that.


        [HttpPost("[action]")]
        public IActionResult Remove([FromBody] RemoveModel<int> rm)
        {
            var gate = _context.Find<Gate>(rm.Key);
            _context.Remove(gate);
            _context.SaveChanges();
            return StatusCode(StatusCodes.Status204NoContent);
        }

        [HttpPost("[action]")]
        public IActionResult InsertUpdate([FromBody] EditModel<GateViewModel> em)
        {
            var gate = mapper.Map<Gate>(em.Value);
            switch (em.Action.ToLower())
            {
                case "update":
                    _context.Entry(gate).CurrentValues.SetValues(gate);
                    _context.Update(gate);
                    _context.SaveChanges();
                    break;
                case "insert":
                    _context.Add(gate);
                    _context.SaveChanges();
                    em.Value.Id = gate.Id;
                    break;
                default:
                    return BadRequest("Action is invalid");
            }
            return Json(em.Value); // em.Value is GateViewModel
        }
        

3 Replies

PS Pavithra Subramaniyam Syncfusion Team March 12, 2018 09:41 AM UTC

Hi I K, 

We have checked your query and we could not reproduce the issue at our end. We have prepared a sample based on you code. Please refer to the below code example , response screenshot and sample link. 

[component.ts] 
@Component({ 
    selector: 'my-app', 
    template: `<ejs-grid #grid [dataSource]='data' [editSettings]='editSettings' [toolbar]='toolbar' [allowPaging]='true' > 
                <e-columns> 
                    <e-column field='OrderID' headerText='Order ID'  isPrimaryKey= 'true'  [isIdentity]="true" [visible]='false' width=120></e-column> 
                .   .   . 
                </e-columns> 
                                                           
                </ejs-grid>` 
}) 
export class AppComponent implements OnInit { 
 
    ngOnInit(): void { 
        this.toolbar = ['Add', 'Edit', 'Delete']; 
        this.editSettings = { allowEditing: true, allowAdding: true, allowDeleting: true, mode:'Dialog' }; 
        this.data = new DataManager({ 
            url: "/Home/DataSource", 
            updateUrl: "Home/Update", 
            insertUrl: "Home/Insert", 
            removeUrl: "Home/Delete", 
            adaptor: new UrlAdaptor 
         });  
    } 
} 


[Homecontroller.cs] 
public ActionResult Update(EditableOrder value) 
        { 
            OrderRepository.Update(value); 
            return Json(value, JsonRequestBehavior.AllowGet); 
        } 
        public ActionResult Insert(EditableOrder value) 
        { 
            OrderRepository.Add(value); 
            return Json(data, JsonRequestBehavior.AllowGet); 
        } 

[response] 
 
[in client] 
 



Could you please share more details on your issue that will be helpful for us to provide a better solution. 

  1. Share the Essential JavaScript 2 package version, you are using.
  2. Share the stack trace, if any script error has thrown.
  3. Please reproduce the issue in the provided sample if possible.
 
Regards, 
Pavithra S. 



IK I K March 12, 2018 01:39 PM UTC

Thanks.

I am using Aspnet Core 2.0 app with angular 5 cli.
I am using latest npm packages for grid and rest syncfusion controls
No error can be found in console of Chrome

My controller:

    [Produces("application/json")]
    [Route("api/Gates")]
    public class GatesController : Controller
    {
        private readonly AppDbContext _context;

        public GatesController(AppDbContext context)
        {
            _context = context;
        }

        [HttpPost("[action]")]
        public IActionResult GetByDataManager([FromBody] DataManager dm)
        {
            var query = _context.Gates.AsQueryable();
            //extension methods in Assembly Syncfusion.EJ, Version=16.1600.0.24, Culture=neutral, PublicKeyToken=null
            if (dm.Where?.Count > 0)
                query = query.PerformWhereFilter(dm.Where.ToWhereFilter(), dm.Where[0].Operator);  
            var totalCount = query.Count();
            if (dm.Sorted?.Count > 0)
                query = query.PerformSorting(dm.Sorted.ToSortedColumns());
            if (dm.Skip != 0)
                query = query.PerformSkip(dm.Skip);
            if (dm.Take != 0)
                query = query.PerformTake(dm.Take);
            return Json(new Result
            {
                result = query.ToList(),
                count = totalCount
            });
        }

        [HttpPost("[action]")]
        public IActionResult Remove([FromBody] RemoveModel rm)
        {
            var gate = _context.Find(rm.Key);
            _context.Remove(gate);
            _context.SaveChanges();
            return Json(gate);
        }

        [HttpPost("[action]")]
        public IActionResult InsertUpdate([FromBody] EditModel em)
        {
            var gate = em.Value;
            switch (em.Action.ToLower())
            {
                case "update":
                    _context.Entry(gate).CurrentValues.SetValues(gate);
                    _context.Update(gate);
                    _context.SaveChanges();
                    break;
                case "insert":
                    _context.Add(gate);
                    _context.SaveChanges();
                    em.Value.Id = gate.Id;
                    break;
                default:
                    return BadRequest("Action is invalid");
            }
            return Json(em.Value);
        }
}


Other classes

public abstract class DMLModel
    {
        public string Action { get; set; }
        public string Table { get; set; }
    }

    public class EditModel : DMLModel
    {
        public T Value { get; set; }
    }
    
    public class RemoveModel : DMLModel
    {
        public string KeyColumn { get; set; }
        public TKey Key { get; set; }
    }


    public class Result
    {
        public IList result;
        public int count;

        public Result()
        {

        }

        public Result(IList result)
        {
            count = result.Count;
            this.result = result;
        }

    }

    public class DataManager
    {
        public int Skip { get; set; }

        public int Take { get; set; }

        public string Tab { get; set; }

        public int[] DraggedRow { get; set; }
        public int Position { get; set; }

        public bool RequiresCounts { get; set; }

        public List Where { get; set; }

        public List Search { get; set; }

        public List Sorted { get; set; }

        public List Group { get; set; }

        public List Select { get; set; }
    }

    public class Sort
    {
        public string Name { get; set; }
        public string Direction { get; set; }
    }

    public class Wheres
    {
        public List Predicates { get; set; }
        public string Field { get; set; }
        public bool IgnoreCase { get; set; }

        public bool IsComplex { get; set; }

        public string Value { get; set; }
        public string Operator { get; set; }
        public string Condition { get; set; }
    }

    public class Predicates
    {

        public string Value { get; set; }
        public string Field { get; set; }

        public bool IsComplex { get; set; }

        public bool IgnoreCase { get; set; }
        public string Operator { get; set; }

    }

    public class Search
    {
        public string[] Fields { get; set; }
        public bool IgnoreCase { get; set; }
        public string Key { get; set; }
        public string Operator { get; set; }
    }

public static class SyncfusionExtensions
    {
        public static string CapitalizeFirstLetter(this string name)
            => name.First().ToString().ToUpper() + name.Substring(1);

        public static Result ToResult(this IList result)
            => new Result(result);

        public static List ToSortedColumns(
            this IEnumerable sorts)
        {
            return sorts.Select(s => new Syncfusion.JavaScript.Models.SortedColumn
            {
                Field = s.Name,
                Direction = (Syncfusion.JavaScript.SortOrder)
                    Enum.Parse(typeof(Syncfusion.JavaScript.SortOrder), s.Direction, true)
            }).ToList();
        }

        public static List ToWhereFilter(
            this IEnumerable wheres) => wheres.First().Predicates.ToPredicates();

        public static List ToPredicates(
            this IEnumerable predicates)
        {
            return predicates.Select(p => new Syncfusion.JavaScript.WhereFilter
            {
                Field = p.Field.CapitalizeFirstLetter(),
                IsComplex = p.IsComplex,
                Operator = p.Operator,
                IgnoreCase = p.IgnoreCase,
                value = p.Value,
                predicates = new List(),
                Condition = ""
            }).ToList();
        }
    }





VA Venkatesh Ayothi Raman Syncfusion Team March 14, 2018 04:58 PM UTC

Hi Customer, 

Thanks for the update. 

We went through your code example that you have share for us and found that you are using WebAPI service controller to bound the Grid data and perform the CRUD operation. So, we suggest you to use WebApiAdaptor instead of UrlAdaptor. Please refer to the following code example, 
Code example
[ts file] 
ngOnInit(): void { 
       
        this.data = new DataManager({ 
            url: '/api/Orders', 
            adaptor: new WebApiAdaptor             
        }); 
        
   

If we use WebApiAdaptor then we don’t need to mention the insertUrl,updateUrl and removeUrl to perform the CRUD operation. Since, WebApI controller has built-in support of read, write and delete operation. Please refer to the following code example, 
// POST: api/Orders 
        [HttpPost] 
        public object Post([FromBody]OrdersDetails value) 
        { 
            OrdersDetails.GetAllRecords().Insert(0, value); 
            return value; 
        }  
 
 [HttpPut] 
        // PUT: api/Orders/5 
public object Put(int id, [FromBody]OrdersDetails value) 
        { 
 
 
            var ord = value; 
            OrdersDetails val = OrdersDetails.GetAllRecords().Where(or => or.OrderID == ord.OrderID).FirstOrDefault(); 
            val.OrderID = ord.OrderID; 
            val.EmployeeID = ord.EmployeeID; 
            val.CustomerID = ord.CustomerID; 
            val.Freight = ord.Freight; 
            val.OrderDate = ord.OrderDate; 
            val.ShipCity = ord.ShipCity; 
            return value; 
        } 
         
        // DELETE: api/ApiWithActions/5 
        [HttpDelete("{id:int}")] 
        [Route("Orders/{id:int}")] 
        public object Delete(int id) 
        { 
            OrdersDetails.GetAllRecords().Remove(OrdersDetails.GetAllRecords().Where(or => or.OrderID == id).FirstOrDefault()); 
            return Json(id); 
        } 

We have also prepared a sample for your convenience which can be download from following link, 

Please let us know if you know if you have any further assistance on this. 

Regards, 
Venkatesh Ayothiraman. 


Loader.
Up arrow icon