Unable to do CRUD in Grid using ASP.NET MVC5 Controller

Here is my Grid code:

@using Syncfusion.EJ2

<div class="row">

    <div class="col control-section">

        @Html.EJS().Grid("Grid").DataSource(ds => ds.Url("/Users/Get").InsertUrl("/Users/Insert").RemoveUrl("/Users/Delete").UpdateUrl("Users/Update").Adaptor("WebApiAdaptor")).AllowSorting().Columns(col =>

        {

            //col.Field("ID").HeaderText("ID").IsPrimaryKey(true).Width("140").ValidationRules(new { required = true, number = true }).TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add();

            col.Field("FirstName").HeaderText("First Name").Width("150").ValidationRules(new { required = true, minLength = 3 }).Add();

            col.Field("LastName").HeaderText("Last Name").Width("150").ValidationRules(new { required = true, minLength = 3 }).Add();

            col.Field("IsSubscribed").HeaderText("Is Subscribed").EditType("booleanedit").DisplayAsCheckBox(true).Type("boolean").Width("150").Add();

            col.Field("LastContactDate").HeaderText("Last Contact Date").EditType("datetimepickeredit").Width("150").Format(new { type = "datetime", format = "M/d/y hh:mm a" }).Add();

        }).ActionBegin("actionBegin").AllowPaging().PageSettings(page => page.PageCount(2)).EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).AllowDeleting(true).Mode(Syncfusion.EJ2.Grids.EditMode.Normal); }).Toolbar(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" }).Render()

    </div>

</div>

<script>

    function actionBegin(args) {

        var grid = document.getElementById("InlineEditing").ej2_instances[0];

        if (args.requestType === 'save') {

            args.index = (grid.pageSettings.currentPage * grid.pageSettings.pageSize) - grid.pageSettings.pageSize;

        }

    }

</script>

Controller:

    public class UsersController : Controller

    {

        private ApplicationDbContext _context = new ApplicationDbContext();


        [HttpGet]

        public ActionResult Get()

        {

            var users = _context.Users.Select(m => new UserViewModel

            {

                ID = m.ID,

                FirstName = m.FirstName,

                LastName = m.LastName,

                LastContactDate = m.LastContactDate,

            });

            return Json(users.ToList(), JsonRequestBehavior.AllowGet);

        }

        // POST: Users/Insert

        [HttpPost]

        public async Task<ActionResult> Insert([Bind(Include = "ID,FirstName,LastName,LastContactDate")] Users user)

        {

            if (ModelState.IsValid)

            {

                _context.Users.Add(user);

                await _context.SaveChangesAsync();

                return new HttpStatusCodeResult(HttpStatusCode.Created);

            }

            return Json(user, JsonRequestBehavior.AllowGet);

        }


        // POST: Users/Update/5

        [HttpPost]

        public async Task<ActionResult> Update([Bind(Include = "ID,ProductID,PlanID,UserGUID,UserID,Password,FirstName,LastName,IsSubscribed,LastContactDate,AuthDigits,EnableTwoFactor,TwoFactorNumber,TwoFactorCountryCode,AuthEmailSent,AuthSMSSent,IsAuthenticated,StatusID,ActiveID,UserFlag,UserField1,UserField2,UserField3")] Users user)

        {

            if (ModelState.IsValid)

            {

                _context.Entry(user).State = EntityState.Modified;

                await _context.SaveChangesAsync();

                return new HttpStatusCodeResult(HttpStatusCode.OK);

            }

            return Json(user, JsonRequestBehavior.AllowGet);

        }


        [HttpGet]

        public async Task<ActionResult> Delete(long? id)

        {

            if (id == null)

            {

                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);

            }

            Users users = await _context.Users.FindAsync(id);

            if (users == null)

            {

                return HttpNotFound();

            }

            _context.Users.Remove(users);

            await _context.SaveChangesAsync();

            return new HttpStatusCodeResult(HttpStatusCode.OK);

        }


        protected override void Dispose(bool disposing)

        {

            if (disposing)

            {

                _context.Dispose();

            }

            base.Dispose(disposing);

        }

    }


The grid doesn't show any data. All of the examples in the documentation are unfortunately useless. It is such a simple example and it is not in the documentation. Please help!


6 Replies

RR Rajapandi Ravi Syncfusion Team March 17, 2022 02:56 PM UTC

Hi Junaid, 

Greetings from Syncfusion support 

For your convenience we have prepared a sample for webApi Adaptor with crud actions. Please find the below code example and sample for more information. 

While binding webApi adator to the Grid, While performing CRUD actions The dataManager will make the server side requests through network requests with PUT, POST, DELETE Request types. Please refer the below screenshots for more information. 

While adding a record 

 

While deleting 
 
 
 
While updating: 
 
 
Based on the request we need to handle perform the CRUD operations in the data source and return the data. 

 
    var data = new ej.data.DataManager({ 
    url: '/api/Order', 
    adaptor: new ej.data.WebApiAdaptor() 
}); 
 
var grid = new ej.grids.Grid({ 
    dataSource: data, 
. . . 
    height: 273 
}); 
    grid.appendTo('#Grid'); 
 
[OrderController] 
namespace EJ2Grid.Controllers 
{ 
    [Produces("application/json")] 
    [Route("api/Order")] 
    public class OrderController : Controller 
    { 
        // GET: api/Orders 
        [HttpGet] 
 
        public object Get() 
        { 
            var queryString = Request.Query; 
 
            int skip = Convert.ToInt32(queryString["$skip"]); 
            int take = Convert.ToInt32(queryString["$top"]); 
            var data = OrdersDetails.GetAllRecords().ToList(); 
            return take != 0 ? new { Items = data.Skip(skip).Take(take).ToList(), Count = data.Count() } : new { Items = data, Count = data.Count() }; 
 
        } 
 
        // GET: api/Orders/5 
        [HttpGet("{id}", Name = "Get")] 
        public string Get(int id) 
        { 
            return "value"; 
        } 
 
        // POST: api/Orders 
        [HttpPost] 
// for insert action 
        public object Post([FromBody]OrdersDetails value) 
        { 
            OrdersDetails.GetAllRecords().Insert(0, value); 
            return value; 
        } 
 
 
 
        // PUT: api/Orders/5 
        [HttpPut] 
// for update action 
        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}")] 
// for delete action 
        public object Delete(int id) 
        { 
            OrdersDetails.GetAllRecords().Remove(OrdersDetails.GetAllRecords().Where(or => or.OrderID == id).FirstOrDefault()); 
            return Json(id); 
        } 
 
        public class Data 
        { 
 
            public bool requiresCounts { get; set; } 
            public int skip { get; set; } 
            public int take { get; set; } 
        } 
    } 
} 



Please let us know, if you need further assistance. 

Regards, 
Rajapandi R 



JU Junaid March 17, 2022 07:17 PM UTC

Thanks for the reply. Unfortunately, this is a JS-based grid. I need to use the MVC5 grid strictly. 



JU Junaid March 18, 2022 11:56 AM UTC

I have followed this and got it working: https://ej2.syncfusion.com/aspnetmvc/documentation/grid/editing/persisting-data-in-server?cs-save-lang=1&cs-lang=razor


I am facing a few more issues:

1) After adding a new row, the topmost row is automatically selected/highlighted (grey background) while the newly added row is at the bottom.


2) To solve the above issue easily, I thought about changing the position of the newly added row in the grid from bottom to top. I have specified .NewRowPosition(Syncfusion.EJ2.Grids.NewRowPosition.Top) ​in EditSettings of the grid, however, the newly added row still shows at the bottom.



RR Rajapandi Ravi Syncfusion Team March 18, 2022 12:51 PM UTC

Hi Junaid, 

Thanks for the update. 

As per your requirement we have prepared a sample of WebApi adaptor in ASP.NET MVC platform. Please refer the below code example and sample for more information. 


 
@Html.EJS().Grid("Grid").DataSource(dataManger => 
       { 
           dataManger.Url("/api/Orders").CrossDomain(true).Adaptor("WebApiAdaptor"); 
       }).Columns(col => 
       { 
 
           col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).Width("120").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add(); 
           col.Field("CustomerID").HeaderText("Customer Name").Width("150").Add(); 
           col.Field("Freight").HeaderText("Freight").Width("120").Format("C2").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add(); 
           col.Field("OrderDate").HeaderText("Order Date").Width("150").Format("yMd").TextAlign(Syncfusion.EJ2.Grids.TextAlign.Right).Add(); 
           col.Field("ShipName").HeaderText("Ship Name").Width("150").Add(); 
           col.Field("ShipCountry").HeaderText("Ship Country").Width("150").Add(); 
 
       }).AllowPaging().PageSettings(page => page.PageSize(5)).EditSettings(edit => { edit.AllowAdding(true).AllowEditing(true).AllowDeleting(true).Mode(Syncfusion.EJ2.Grids.EditMode.Normal); }).Toolbar(new List<string>() { "Add", "Edit", "Delete", "Update", "Cancel" }).Render() 
 


Regards, 
Rajapandi R 



JU Junaid replied to Junaid March 18, 2022 07:00 PM UTC

I already have it working using the "UrlAdaptor" as mentioned in my previous comment. Kindly answer how to fix these two issues that I am facing after implementing the CRUD operations in Grid: http://www.syncfusion.com/forums/173706/unable-to-do-crud-in-grid-using-asp-net-mvc5-controller?reply=S2J2Cr



RR Rajapandi Ravi Syncfusion Team March 21, 2022 01:50 PM UTC

Hi Junaid, 

Thanks for the update. 

Query#: After adding a new row, the topmost row is automatically selected/highlighted (grey background) while the newly added row is at the bottom. 

By default, in our Grid, when the record is added at Top or bottom position the selection will happens at the 1st row position. This was the default behavior. 

You can prevent this action and select the newly added row at bottom at its modified index by cancelling the row selection for this case(setting ‘true’ to event arguments ‘cancel’ property) in the Grid’s rowSelecting event and then selecting the new row index using its selectRow method. Please refer the below code example for more information. 

 
<script> 
    var newRowAdded = false; 
    function selecting(args) { //rowSelecting event of Grid 
        if (newRowAdded) { 
            newRowAdded = false; 
            // Selection is cancelled if it is new row added at bottom case(using global variable) 
            if (this.editSettings.newRowPosition == 'Bottom') { 
                args.cancel = true; 
                // The newly added row index is selected 
                this.selectRow(this.currentViewData.length - 1); 
            } 
        } 
    } 
    function begin(args) { //actionBegin event of Grid 
        if (args.requestType === "save" || args.action === "add") { 
            newRowAdded = true; 
        } 
    } 
</script> 
 



Query#: however, the newly added row still shows at the bottom. 

You can display the newly added record at top by inserting the added record in the 0th position at the server side. Please refer the below code example and video demo for more information. 

HomeController.cs 
 
public ActionResult Insert(OrdersDetails value) 
        { 
            var ord = value; 
            orddata.Insert(0,ord); //this helps to insert the newly added record in the 1st row position to the list 
            return Json(value); 
        } 
 


Regards, 
Rajapandi R 


Loader.
Up arrow icon