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

Mvc 5 CRUD example using a Grid with entityframework 6x

Hi Guys you have a wonderful product I am really enjoying it, I am struggling a bit with data binding and need help  to create a Grid with CRUD using Mvc5 and entity framework 6.x code first, and Jason

Do you have an example that satisfies the above.

Model could be simple

User

  • UserId
  • FirstName
  • LastName
  • Age

Many thanks in advance

Edmund Herbert



12 Replies

MS Madhu Sudhanan P Syncfusion Team February 2, 2015 02:05 PM UTC

Hi Edmund,

Thanks for using Syncfusion Products.

We are working on your query with high priority and we will update you further details on February 3, 2015. Thanks for your patience in advance.

Regards,

Madhu Sudhanan. P




MS Madhu Sudhanan P Syncfusion Team February 3, 2015 09:59 AM UTC

Hi Edmund,

We appreciate your patience. We have created a ASP.Net MVC Grid sample that would satisfy your requirement  (Mvc 5 CRUD example using a Grid with entityframework 6x) and the same can be downloaded from the below location.

Sample Location: EntityCodeFirst220222522.zip

For your kind information, the above sample is created using Essential Studio v12.4.0.24 and please use our latest version to run the sample. You can find the Essential studio v12.4.0.24 in the below link.

https://www.syncfusion.com/forums/117834/essential-studio-2014-volume-4-final-release-v12-4-0-24-available-for-download

We have achieved the following things in the above sample.

1. Created Entity Mode through code first technique.

2. Bound the Grid with the data from entity model using UrlAdaptor of DataManager.

[cshtml]

@(Html.EJ().Grid<OrderTable>("Grid")

        .Datasource(ds => ds.URL("GetOrderData")

                            .InsertURL("PerformInsert")

                            .UpdateURL("PerformUpdate")

                            .RemoveURL("PerformDelete")

                            .Adaptor(AdaptorType.UrlAdaptor)

                            )

        .AllowPaging()

        .EditSettings(e => e.AllowEditing()

                            .AllowDeleting()

                            .AllowAdding()

                            .EditMode(EditMode.Normal)

                                )

        .ToolbarSettings(tool => tool.ShowToolbar().ToolbarItems(item =>

            {

                item.AddTool(ToolBarItems.Add);

                item.AddTool(ToolBarItems.Edit);

                item.AddTool(ToolBarItems.Delete);

                item.AddTool(ToolBarItems.Update);

                item.AddTool(ToolBarItems.Cancel);

            }))

        .Columns(col =>

                {

                    col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).TextAlign(TextAlign.Right).Width(75).Add();

                    col.Field("EmployeeID").HeaderText("Employee ID").TextAlign(TextAlign.Right).Width(75).Add();

                    col.Field("CustomerID").HeaderText("Customer ID").TextAlign(TextAlign.Left).Width(75).Add();                   

                }))

The Adaptors are used to handle the request and response to and from the server. Please refer the below online UG for list of adaptors available for our DataManager.

https://help.syncfusion.com/js/datamanager/data-adaptors

3. And now CRUD operations in grid are performed at controller based on the posted data as follows.

        //Provide grid datasource

        public ActionResult GetOrderData()

        {

            var result = new OrderContext().OrderTables.ToList();

            return Json(new { result = result, count = result.Count }, JsonRequestBehavior.AllowGet);

        }

        //Perform file insertion

        public ActionResult PerformInsert(EditParams param)

        {

           

            OrderContext db = new OrderContext();

            db.OrderTables.Add(param.value);

            db.SaveChanges();

            return RedirectToAction("GetOrderData");

        }

        //Perform update

        public ActionResult PerformUpdate(EditParams param)

        {

            OrderContext db = new OrderContext();

            OrderTable table = db.OrderTables.Single(o => o.OrderID == param.value.OrderID);

            db.Entry(table).CurrentValues.SetValues(param.value);

            db.Entry(table).State = EntityState.Modified;

            db.SaveChanges();

            return RedirectToAction("GetOrderData");

        }

        //Perform delete

        public ActionResult PerformDelete(int key, string keyColumn)

        {

            OrderContext db = new OrderContext();

            db.OrderTables.Remove(db.OrderTables.Single(o => o.OrderID == key));

            db.SaveChanges();

            return RedirectToAction("GetOrderData");

        }

In the above code snippet, EditParams is a simple user-defined class to perform model binding and get the posted data.

Please refer the below link for more information for performing CRUD operation in grid at server side.

https://help.syncfusion.com/js/datamanager/cruddataoperations

https://www.syncfusion.com/kb/3013/how-to-change-the-url-action-path-for-the-grid-crud-operations

                                                                                  

Please let us know if you have any queries

Regards,

Madhu Sudhanan. P




EH Edmund Herbert February 15, 2015 05:19 PM UTC

Hi Madhu,

Thank you for your example it helped me a lot I am now stumped on sorting an filtering I have looked at documentation, if you are using jason do you have to use jquery to sort.

Thanks in advance.

Regards

Edmund Herbert



MS Madhu Sudhanan P Syncfusion Team February 16, 2015 01:35 PM UTC

Hi Edmund,

Please find the response.

Query:  I am now stumped on sorting an filtering I have looked at documentation, if you are using json do you have to use jquery to sort.

While using remote binding datasource, all the grid actions such as filtering, grouping and sorting should be handled at the server side itself. But in the previously provided sample, we didn’t performed such operations and hence grid actions were not worked.

Now we have modified the controller`s action to handle the grid actions and please refer the below code snippet.

using Syncfusion.JavaScript;

using Syncfusion.JavaScript.DataSources;

       //Provide grid datasource

        public ActionResult GetOrderData(DataManager dm)

        {

            IEnumerable data = new OrderContext().OrderTables.ToList();

            int count = new OrderContext().OrderTables.ToList().Count;

            DataOperations operation = new DataOperations();

            //Performing filtering operation

            if (dm.Where != null)

            {

                data = operation.PerformWhereFilter(data, dm.Where, "and");

                var filtered = (IEnumerable<object>)data;

                count = filtered.Count();

            }

            //Performing sorting operation

            if (dm.Sorted != null)

                data = operation.PerformSorting(data, dm.Sorted);

            //Performing paging operations

            data = operation.PerformSkip(data, dm.Skip);

            data = operation.PerformTake(data, dm.Take);

          

            return Json(new { result = data, count = count }, JsonRequestBehavior.AllowGet);

        }

In the above, we have used DataOperation class to perform the server side action such as filtering, sorting and paging.

While sorting, the posted header information will be bound to the properties of DataManager as below.

For your convenience we have modified the previously provided sample with the above snippet and the same can be downloaded from the below location.

Sample Location: https://www.syncfusion.com/downloads/support/directtrac/general/EntityCodeFirst_AllOperation-1213836315.zip

Please let us know if you have any queries.

Regards,

Madhu Sudhanan. P




DA David replied to Madhu Sudhanan P July 2, 2015 01:36 PM UTC

Hi Edmund,

Please find the response.

Query:  I am now stumped on sorting an filtering I have looked at documentation, if you are using json do you have to use jquery to sort.

While using remote binding datasource, all the grid actions such as filtering, grouping and sorting should be handled at the server side itself. But in the previously provided sample, we didn’t performed such operations and hence grid actions were not worked.

Now we have modified the controller`s action to handle the grid actions and please refer the below code snippet.

using Syncfusion.JavaScript;

using Syncfusion.JavaScript.DataSources;

       //Provide grid datasource

        public ActionResult GetOrderData(DataManager dm)

        {

            IEnumerable data = new OrderContext().OrderTables.ToList();

            int count = new OrderContext().OrderTables.ToList().Count;

            DataOperations operation = new DataOperations();

            //Performing filtering operation

            if (dm.Where != null)

            {

                data = operation.PerformWhereFilter(data, dm.Where, "and");

                var filtered = (IEnumerable<object>)data;

                count = filtered.Count();

            }

            //Performing sorting operation

            if (dm.Sorted != null)

                data = operation.PerformSorting(data, dm.Sorted);

            //Performing paging operations

            data = operation.PerformSkip(data, dm.Skip);

            data = operation.PerformTake(data, dm.Take);

          

            return Json(new { result = data, count = count }, JsonRequestBehavior.AllowGet);

        }

In the above, we have used DataOperation class to perform the server side action such as filtering, sorting and paging.

While sorting, the posted header information will be bound to the properties of DataManager as below.

For your convenience we have modified the previously provided sample with the above snippet and the same can be downloaded from the below location.

Sample Location: http://www.syncfusion.com/downloads/support/directtrac/general/EntityCodeFirst_AllOperation-1213836315.zip

Please let us know if you have any queries.

Regards,

Madhu Sudhanan. P



HI!

i dont understand it... filter is apply to a lista, not to a query

IEnumerable data = new OrderContext().OrderTables.ToList();

So...i think filters should be applied to SQL statements not on lists...¿no?

Sample:

OrderContext().OrderTables.Where(a=>a.Id >= 5).toList();


Filter is executed by sql engine, no to a lista with all results... So, ¿exist some way to apply filters to sql query directly?

Sorry for my English! 

Thanks!



MS Madhu Sudhanan P Syncfusion Team July 3, 2015 12:10 PM UTC

Hi Edmund,

In our previous update, we have used the DataOperation to perform the server side operation. The DataOperation will work on IEnumerable/IQueryable and not directly on DbSet<T> and hence to use DataOperation we have to provide the data as IEnumerable and hence the data was fetched from the database as follows. This is the default behavior of DataOperation.


IEnumerable data = new OrderContext().OrderTables.ToList();


DataOperations operation = new DataOperations();

//Performing filtering operation

if (dm.Where != null)

{

//Processes after the whole data is retrieved from DB.

data = operation.PerformWhereFilter(data, dm.Where, "and");

. . . .
}


If you don’t want to fetch data as did in the above behavior, you can use the default System.Linq to perform the server operation based on the parameter that we obtained using DataManager and return the result as a pair of result and count.

And also please refer the below knowledge base for the available properties of DataManager class(see Table1 : Query parameters).

https://www.syncfusion.com/kb/4300/server-side-api-for-datamanager-operations

Please let us know if you require further assistance.

Regards,
Madhu Sudhanan. P


BW Brent Welke May 4, 2016 05:21 PM UTC

When i try this sample in Visual Studio 2015 I get the following error:

Compiler Error Message: CS1660: Cannot convert lambda expression to type 'Syncfusion.JavaScript.DataSource' because it is not a delegate type

Source Error:

Line 15: 
Line 16:     @(Html.EJ().Grid<OrderTable>("Grid")
Line 17:         .Datasource(ds => ds.URL("GetOrderData")
Line 18:                             .InsertURL("PerformInsert")
Line 19:                             .UpdateURL("PerformUpdate")

Source File: d:\Inetpub\wwwroot\Syncfusion\support\EntityCodeFirst\EntityCodeFirst\Views\Home\Index.cshtml    Line: 17 


PK Prasanna Kumar Viswanathan Syncfusion Team May 5, 2016 11:19 AM UTC

Hi Brent, 

We run the sample in VS 2015 and we were unable to reproduce the mentioned  issue at our end. We suspect that the mentioned issue is occur due to DLL Conflict. To avoid this issue, Please make sure the following things before build your application.

1)  Syncfusion dependent assemblies must be of the same version in the web.config file according to the project application framework. When the project application has reference to the Syncfusion DLL’s Syncfusion.EJ and Syncfusion.EJ.MVC and when those DLLs are mentioned with different versions as given in the following code example, then the DLL Conflict arises.
 
<assemblies> 
        <add assembly="Syncfusion.EJ, Version=14.1400.0.41, Culture=neutral, PublicKeyToken=3d67ed1f87d44c89" /> 
        <add assembly="Syncfusion.EJ.Mvc, Version=14.1450.0.41, Culture=neutral, PublicKeyToken=3d67ed1f87d44c89" /> 
</assemblies> 

So, please ensure Syncfusion.EJ and Syncfusion.EJ.MVC version in web.config file as same as you are referring the dll in the Reference.
 

2) Before run the sample, please delete bin and obj folder in your sample.
 
For your convenience we attached a sample in version(14.1.0.41) and download the sample from the following link 
If you still face the same issue, please get back to us with the current version of Syncfusion controls that you are using in your sample. 
Regards, 
Prasanna Kumar N.S.V 
 



CA carlosgutierrez March 14, 2017 09:12 PM UTC

good day,

very thanks for the example.  i am using it.  sorry my english.  i add a new class and i want to show the data as grid hierarchil but it doesn't work for me.  you could help me with a example.  very much so thanks.  

carlosg.


TS Thavasianand Sankaranarayanan Syncfusion Team March 15, 2017 01:30 PM UTC

Hi Carlosg, 
 
We have analyzed your query and we suspect that you want create hierarchical grid with Url Adaptor enabled. 
 
In the attached sample we have enable the Url Adaptor for the child Grid also. In the child Grid data retrieved based on the given QueryString in the child Grid. 
 
Refer the below code example. 
 
 
@(Html.EJ().Grid<EmployeeView>("HierarchyGrid") 
        .Datasource(ds => ds.URL(@Url.Action("DataSource")).Adaptor(AdaptorType.UrlAdaptor)) 
        .Columns(col => 
        { 
            col.Field("EmployeeID").HeaderText("Employee ID").IsPrimaryKey(true).TextAlign(TextAlign.Right).Width(75).Add(); 
             
          --------------------- 
 
       }) 
                 .ChildGrid(child => 
                 { 
                     child.Datasource(ds => ds.URL(@Url.Action("DataSource2")).Adaptor(AdaptorType.UrlAdaptor)) 
 
                        .QueryString("EmployeeID") 
                        .AllowPaging() 
                        .Columns(col => 
                        { 
                            col.Field("OrderID").HeaderText("OrderID").IsPrimaryKey(true).TextAlign(TextAlign.Right).Width(75).Add(); 
                             
                         ------------- 
 
                        }) 
                        .ChildGrid(d => 
                        { 
                      d.Datasource(dt => dt.URL(@Url.Action("DataSource3")).Adaptor(AdaptorType.UrlAdaptor)) 
 
                           .QueryString("CustomerID") 
                           .Columns(col => 
                        { 
                                 col.Field("CustomerID").HeaderText("CustomerID").IsPrimaryKey(true).TextAlign(TextAlign.Right).Width(75).Add(); 
                             
                        ---------------- 
 
                       }); 
                        }); 
                 }) 
 
) 
 
 
We have prepared a sample and it can be downloadable from the below location. 
 
 
Refer the help documentation. 
 
 
 
 
Regards, 
Thavasianand S. 



BR Bernadus Rangga Kresna Waskita February 26, 2022 03:20 PM UTC

hi everyone, im really strugling with crud ef, can you explain EditParams please, is it a class that i need to create? can u help provide example with this ordercontext as example if it needs editparams class


im getting error that said at the parameter


 public ActionResult PerformInsert(EditParams param) <<= here it said EditParams could not be found




        {....



FS Farveen Sulthana Thameeztheen Basha Syncfusion Team February 28, 2022 02:07 PM UTC

Hi Bernadus, 

Query#:- can u help provide example with this ordercontext as example if it needs editparams class 

We have created sample using Entity Framework model which can be downloaded from the below location:- 

Documentation link:- 

Also we have used OrderRepositary as dataSource(db) and  EditableOrder is the corresponding model Class. We can use it as (EditableOrder or EditParams) depends upon the own Model class. 
 
Refer to the code below:- 
GridFeatures.cshtml:- 
 
@(Html.EJ().Grid<object>("FlatGrid") 
           .Datasource(ds => ds.URL("/Grid/DataSource").UpdateURL("/Grid/Update").InsertURL("/Grid/Insert").Adaptor(AdaptorType.UrlAdaptor)) 
        .AllowScrolling() 
          
        .Columns(col => 
        { 
            col.Field("OrderID").HeaderText("Order ID").IsPrimaryKey(true).TextAlign(TextAlign.Right).Width(75).Add(); 
 
        }).ClientSideEvents(eve => { eve.ActionFailure("Failure"); })) 
 
GridController:- 
 
public ActionResult DataSource(DataManager dm) 
        { 
            DataOperations ds = new DataOperations(); 
 
            var data = ds.Execute(OrderRepository.GetAllRecords().ToList(), dm); 
            return Json(new { result = data, count = db.Orders.ToList().Count }, JsonRequestBehavior.AllowGet); 
        } 
 
    public ActionResult Insert(EditableOrder value) 
        { 
            OrderRepository.Add(value); 
           var data =  OrderRepository.GetAllRecords(); 
             
            return Json(data, JsonRequestBehavior.AllowGet); 
        } 
 
        public ActionResult Update(EditableOrder value) 
        { 
             
            EditableOrder old = OrderRepository.GetAllRecords().Where(o => o.OrderID == value.OrderID).SingleOrDefault(); 
            return Json(OrderRepository.GetAllRecords(), JsonRequestBehavior.AllowGet); 
        } 
 
    public class EditableOrder 
    { 
        [Range(0, int.MaxValue, ErrorMessage = "OrderID must be greater than 0.")] 
        public int OrderID 
        { 
            get; 
            set; 
        } 
 
        [StringLength(5, ErrorMessage = "CustomerID must be 5 characters.")] 
        public string CustomerID 
        { 
            get; 
            set; 
        } 
        
    } 

Please get back to us if you are facing any difficulties on this. 

Regards, 
Farveen sulthana T 


Loader.
Live Chat Icon For mobile
Up arrow icon