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. (Last updated on: November 16, 2018).
Unfortunately, activation email could not send to your email. Please try again.
Syncfusion Feedback

Mvc 5 CRUD example using a Grid with entityframework 6x

Thread ID:

Created:

Updated:

Platform:

Replies:

118091 Jan 30,2015 06:22 PM UTC Aug 24,2017 04:06 PM UTC ASP.NET MVC 10
loading
Tags: Grid
Edmund Herbert
Asked On January 30, 2015 06:22 PM UTC

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



Madhu Sudhanan P [Syncfusion]
Replied On 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



Madhu Sudhanan P [Syncfusion]
Replied On 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.

http://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.

http://help.syncfusion.com/ug/js/default.htm#!documents/dataadaptors.htm

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.

http://help.syncfusion.com/ug/js/default.htm#!documents/crudoperationwithser.htm

http://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



Edmund Herbert
Replied On 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


Madhu Sudhanan P [Syncfusion]
Replied On 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: 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



David
Replied On 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!


Madhu Sudhanan P [Syncfusion]
Replied On 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

Brent Welke
Replied On 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 

Prasanna Kumar Viswanathan [Syncfusion]
Replied On 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 
 


carlosgutierrez
Replied On 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.

Thavasianand Sankaranarayanan [Syncfusion]
Replied On 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. 


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.

Warning Icon 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.Close Icon

;