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
close icon

grid crud


hi, attached you can find a simple controller, and the grid that which i am trying to bind the crud functions created with the scaffolding. 
can you please help me refactor/change the functions of "Insert", "update", "Delete"(maybe with a confirmation dialog first)
to work with the grid?
thank you



============

@using Syncfusion.JavaScript.Models;
@using Syncfusion.JavaScript;


@model IEnumerable<EventsManager.Models.Tag>

@{
    ViewData["Title"] = "Index";
}
<h2>Tags</h2>
<p>add</p>
<p>your tag</p>
<ej-grid id="FlatGrid"  allow-paging="true" allow-scrolling="true" is-responsive="true"  min-width="500" allow-sorting="true" allow-multi-sorting="true" allow-grouping="true" allow-filtering="true" filter-settings="@(new FilterSettings() { FilterType=FilterType.Excel}) ">
    <e-scroll-settings width=@("100%") height=@("100%")></e-scroll-settings>  
    <e-sort-settings>
        <e-sorted-columns>
            <e-sorted-column field="ID" direction="Ascending" />
            <e-sorted-column field="TagName" direction="Ascending" />
        </e-sorted-columns>
    </e-sort-settings> 

    <e-datamanager json="(IEnumerable<object>)Model" update-url="Tags/Edit" insert-url="Tags/Create" remove-url="Tags/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","excelExport","wordExport","pdfExport" })"></e-toolbar-settings>
    <e-columns>
        <e-column field="ID" header-text="ID" is-primary-key="true" text-align="Left" width="75"></e-column>
        <e-column field="TagName" header-text="Tag Name"></e-column>
    </e-columns>
</ej-grid>
====================

CONTROLLER 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using EventsManager.Data;
using EventsManager.Models;

namespace EventsManager.Controllers
{
    public class TagsController : Controller
    {
        private readonly ApplicationDbContext _context;

        public TagsController(ApplicationDbContext context)
        {
            _context = context;    
        }

        // GET: Tags
        public async Task<IActionResult> Index()
        {
            return View(await _context.Tags.ToListAsync());
        }

        // GET: Tags/Details/5
        public async Task<IActionResult> Details(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var tag = await _context.Tags
                .SingleOrDefaultAsync(m => m.ID == id);
            if (tag == null)
            {
                return NotFound();
            }

            return View(tag);
        }

        // GET: Tags/Create
        public IActionResult Create()
        {
            return View();
        }

        // POST: Tags/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("ID,TagName")] Tag tag)
        {
            if (ModelState.IsValid)
            {
                _context.Add(tag);
                await _context.SaveChangesAsync();
                return RedirectToAction("Index");
            }
            return View(tag);
        }

        // GET: Tags/Edit/5
        public async Task<IActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var tag = await _context.Tags.SingleOrDefaultAsync(m => m.ID == id);
            if (tag == null)
            {
                return NotFound();
            }
            return View(tag);
        }

        // POST: Tags/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for 
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(int id, [Bind("ID,TagName")] Tag tag)
        {
            if (id != tag.ID)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(tag);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!TagExists(tag.ID))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction("Index");
            }
            return View(tag);
        }

        // GET: Tags/Delete/5
        public async Task<IActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var tag = await _context.Tags
                .SingleOrDefaultAsync(m => m.ID == id);
            if (tag == null)
            {
                return NotFound();
            }

            return View(tag);
        }

        // POST: Tags/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(int id)
        {
            var tag = await _context.Tags.SingleOrDefaultAsync(m => m.ID == id);
            _context.Tags.Remove(tag);
            await _context.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        private bool TagExists(int id)
        {
            return _context.Tags.Any(e => e.ID == id);
        }
    }
}



4 Replies

HA Hassan April 24, 2017 08:54 AM UTC

Hi , 




        private readonly ApplicationDbContext _context;

        public TagsController(ApplicationDbContext  context)
        {
            _context = context;
        }

      
        public IActionResult Index()
        {
            return View();
        }
        public ActionResult CellEditInsert([FromBody]EditParams value)
        {
            
            var datas = _context;
            value.value.Tkey = _context.Tags.First().tagid- 1;
            datas.Tags.Add(value.value  );
            datas.SaveChanges();
            return Json(value);

                  }
        public class DataResult
        {
            public IEnumerable result { get; set; }
            public int count { get; set; }
            public IEnumerable aggregate { get; set; }
            public IEnumerable groupDs { get; set; }
        }

        public List<Tags> GetData()
        {
           List<Tags> datas = _context.Tags.Take(100).ToList();
            return datas;
        }
        public ActionResult DataSource([FromBody]DataManager dm)
        {

            IEnumerable Result = _context.Tags.Take(100).ToList();
            var count = _context.Tags.AsQueryable().Count();
            DataOperations operation = new DataOperations();
            DataResult result = new DataResult();
            if (dm.Sorted != null && dm.Sorted.Count > 0) //Sorting
            {
                Result = operation.PerformSorting(Result, dm.Sorted);
            }
            if (dm.Where != null && dm.Where.Count > 0) //Filtering
            {
                Result = operation.PerformWhereFilter(Result, dm.Where, dm.Where[0].Operator);
            }
            List<string> str = new List<string>();
            if (dm.Aggregates != null)
            {
                for (var i = 0; i < dm.Aggregates.Count; i++)
                    str.Add(dm.Aggregates[i].Field);
                result.aggregate = operation.PerformSelect(Result, str);
            }
            count = Result.AsQueryable().Count();
            if (dm.Skip != 0)
            {
                Result = operation.PerformSkip(Result, dm.Skip);
            }
            if (dm.Take != 0)
            {
                Result = operation.PerformTake(Result, dm.Take);
            }
            result.result = Result;
            result.count = count;
            return Json(result);

        }



        public ActionResult CellEditUpdate([FromBody] EditParams  value)
        {
            
            var db = _context;
            db.Entry(value.value).State = EntityState.Modified;
            db.SaveChanges();
            return Json(value);

        }

        public  ActionResult   CellEditDelete([FromBody]EditParams  value)
        {
 
            var db = _context;
            Tags order = db.Tags.Where(c => c.tagid  == Convert.ToInt32(value.key)).FirstOrDefault();
            db.Tags.Remove(order);
            db.SaveChanges();
            return Json(order);


        }


HA Hassan April 24, 2017 08:58 AM UTC

in views (Razor syntax)


@{Html.EJ().DataManager("FlatData").URL("/TagsController/DataSource").InsertURL("/TagsController/CellEditInsert").UpdateURL ("/TagsController/CellEditUpdate").RemoveURL ("/TagsController/CellEditDelete").Adaptor(AdaptorType.UrlAdaptor).Render();}*@
@{Html.EJ().Grid<object>("myGrid")
                                                      .DataManagerID("FlatData")
                                                      
                                                       .EditSettings(edit => { edit.AllowAdding().AllowDeleting().AllowEditing().EditMode( EditMode.Batch ); })
                                                      .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);
                                                          });
                                                      })
                                                  .Columns(col =>
                                                  {
                                                      col.Field("tagid").HeaderText("tag1d").IsPrimaryKey(true).IsIdentity(true).Add();
                                                      col.Field("tagname").HeaderText("tagname").Add();
                                                 
                                                  }).Render();
}



DA DAN April 24, 2017 09:09 AM UTC

Hi, thanks for the quick reply. The generated code during scaffolding is using Async programming.
Also I am using grid with edit-mode="@(EditMode.Normal). 

My final "Want" is to use the grid with the above into consideration:
a)Grid dialog Template edit.
b)the grid must load, sort,search,filter etc very large amounts of data efficiently.

Can someone help us to refactor the code for the simple example above. (Tags {ID, TagName} )
I think that will help other people also.



JK Jayaprakash Kamaraj Syncfusion Team April 25, 2017 10:58 AM UTC

Hi Danil, 

Thank you for contacting Syncfusion support. 

We suggest you to use the UrlAdaptor in Grid, which will retrieve data based on the page size (By default page size is 12 when enable the AllowPaging) and works based on the load on demand concept.   

While using UrlAdaptor, you can handle grid operation (paging/filtering/searching/sorting) in server side. When performing paging, filtering, sorting, editing operations on the grid queries are passed to the server side using DataManager class.  
 
Note: skip/take are the queries responsible for handling the paging action  
  
  
The response from server should be wrapped in an object with properties named result to hold the data and count to hold the total records count. To handle the server-side operations, we have Server-side APIs which has been found in the DataOperations class of Syncfusion Libraries. Refer to the following KB.  
  
   
The DataManager class helps in binding the Grid queries passed to the server-side. Based on those queries you can perform server-side operation on the Grid data.   
The query parameters that help you perform the server-side operations are as follows.  
  
Expand   
It is used as OData Expand query.   
RequiresCounts   
When this property is set to True, the total count of records are included in the result.   
Skip   
Details regarding current page are skipped.   
Take   
Used to take required records from data manager.   
Sorted   
Records return the sorted collection.   
Table   
It is a data source table name.   
Where   
Records return the filter collection.   
 
Server side operations such as sorting, filtering, paging are performed bythe PerformSortingPerfomWherFilterPerformSkip and PerformTake methods.   

<ej-grid id="Grid" allow-paging="true" action-complete="complete"> 
    <e-datamanager url="/Home/Data" update-url="/Home/CellEditUpdate" insert-url="/Home/CellEditInsert" remove-url="/Home/CellEditDelete" adaptor="UrlAdaptor" /> 
    <e-edit-settings allow-adding="true" allow-editing="true" dialog-editor-template-id="#template" edit-mode="DialogTemplate" /> 
    <e-toolbar-settings show-toolbar="true" toolbar-items="@(new List<string>() {"add","edit","delete","update","cancel" })" /> 
    <e-columns> 
        <e-column field="OrderID" header-text="Order ID" is-primary-key="true" default-value="0" text-align="Right" width="75"></e-column> 
        <e-column field="CustomerID" header-text="Customer ID" width="80"></e-column> 
        <e-column field="EmployeeID" header-text="Employee ID" text-align="Left" width="75"></e-column> 
       
        <e-column field="Freight" header-text="Freight" format="{0:C2}" text-align=Right width="75"></e-column> 
        <e-column field="ShipCity" header-text="Ship City" width="110"></e-column> 
    </e-columns> 
</ej-grid> 
 
public ActionResult Data([FromBody]DataManager dm) 
        { 
            IEnumerable Data = _context.Orders.Take(100).ToList(); 
 
            Syncfusion.JavaScript.DataSources.DataOperations operation = new Syncfusion.JavaScript.DataSources.DataOperations(); 
            if (dm.Sorted != null && dm.Sorted.Count > 0) //Sorting 
            { 
                Data = operation.PerformSorting(Data, dm.Sorted); 
            } 
            if (dm.Where != null && dm.Where.Count > 0) //Filtering 
            { 
                Data = operation.PerformWhereFilter(Data, dm.Where, dm.Where[0].Operator); 
            } 
            if (dm.Search != null && dm.Search.Count > 0) //searching 
            { 
                Data = operation.PerformSearching(Data, dm.Search); 
            } 
 
            int count = Data.AsQueryable().Count(); 
            if (dm.Skip != 0) 
            { 
                Data = operation.PerformSkip(Data, dm.Skip); 
            } 
            if (dm.Take != 0) 
            { 
                Data = operation.PerformTake(Data, dm.Take); 
            } 
            return Json(new { result = Data, count = count }); 
         
    }    } 

To perform CRUD operation, we need to handle it in server side.  We need to map CRUD operation in Grid to Server-Side Controller action using the properties InsertURLRemoveURL and  UpdateURL. Refer to the sample & code example as below. 

<ej-grid id="Grid" allow-paging="true" action-complete="complete"> 
    <e-datamanager url="/Home/Data" update-url="/Home/CellEditUpdate" insert-url="/Home/CellEditInsert" remove-url="/Home/CellEditDelete" adaptor="UrlAdaptor" /> 
    <e-edit-settings allow-adding="true" allow-editing="true" dialog-editor-template-id="#template" edit-mode="DialogTemplate" /> 
    <e-toolbar-settings show-toolbar="true" toolbar-items="@(new List<string>() {"add","edit","delete","update","cancel" })" /> 
    <e-columns> 
        <e-column field="OrderID" header-text="Order ID" is-primary-key="true" default-value="0" text-align="Right" width="75"></e-column> 
        <e-column field="CustomerID" header-text="Customer ID" width="80"></e-column> 
        <e-column field="EmployeeID" header-text="Employee ID" text-align="Left" width="75"></e-column> 
       
        <e-column field="Freight" header-text="Freight" format="{0:C2}" text-align=Right width="75"></e-column> 
        <e-column field="ShipCity" header-text="Ship City" width="110"></e-column> 
    </e-columns> 
</ej-grid> 
 
HomeController.cs 
 
  public ActionResult CellEditInsert([FromBody]EditParams value) 
        { 
            var datas = _context; 
            datas.Orders.Add(value.value); 
            datas.SaveChanges(); 
            return Json(value); 
        } 
        public ActionResult CellEditUpdate([FromBody]EditParams value) 
        { 
            var db = _context; 
            db.Entry(value.value).State = EntityState.Modified; 
            db.SaveChanges(); 
            return Json(value); 
 
        } 
        public ActionResult CellEditDelete([FromBody]EditParams value) 
        { 
            var db = _context; 
            Orders order = db.Orders.Where(c => c.OrderID == Convert.ToInt32(value.key)).FirstOrDefault(); 
            db.Orders.Remove(order); 
            db.SaveChanges(); 
            return Json(order); 
        } 
 
Model/NORTHWND.cs 
 
public partial class Orders 
    { 
        [Key] 
        public int OrderID { get; set; } 
        public string CustomerID { get; set; } 
        public int EmployeeID { get; set; } 
        public decimal? Freight { get; set; } 
        public DateTime? OrderDate { get; set; } 
        public string ShipCity { get; set   ; } 
    } 
 
    public class EditParams 
    { 
        public string key { get; set; } 
        public string action { get; set; } 
        public string keyColumn { get; set; } 
 
        public Orders value { get; set; } 
    } 

We have prepared a Grid sample with dialog template and UrlAdaptor that can be downloaded from the following link. 


Regards, 

Jayaprakash K. 
 


Loader.
Live Chat Icon For mobile
Up arrow icon