Edit this page

Web API Editing

This article demonstrates how to implement the CRUD (Create, Read, Update, Destroy) data operations with the Kendo UI Grid for ASP.NET MVC and a Web API controller.

Configuration

Below are listed the steps for you to follow when implementing the CRUD data operations with a Web API controller for the Kendo UI Grid for ASP.NET MVC. The configuration example uses the Products table from the Northwind database.

  1. Create a new ASP.NET MVC 4 application. If you have installed the Telerik UI for ASP.NET MVC Visual Studio Extensions, create a Telerik UI for ASP.NET MVC Web application. Name the application KendoGridWebApiCRUD. If you decided not to use the Telerik UI for ASP.NET MVC Visual Studio Extensions, follow the steps from the introductory article to add Telerik UI for ASP.NET MVC to the application.

  2. Add a new Entity Framework Data Model. Right-click the ~/Models folder in the solution explorer and pick Add > New Item. Choose Data > ADO.NET Entity Data Model in the Add New Item dialog. Name the model Northwind.edmx and click Next. This starts the Entity Data Model Wizard.

    Figure 1. A new entity data model

    New entity data model

  3. Select Generate from database and click Next. Configure a connection to the Northwind database. Click Next.

  4. Select the Products table. Leave all other options as they are set by default. Click Finish to create the Entity Framework model.

    Figure 2. Choosing the connection

    Choose the Products table

  5. Right click the Controllers folder in Visual Studio solution explorer. Select Add > Controller.

  6. Set ProductsController as Controller name. Select API controller with read/write actions, using Entity Framework as Template. Select Product (KendoGridWebApiCRUD.Models) as Model class and NorthwindEntities (KendoGridWebApiCRUD.Models) as Data context class. Click Add to create the Web API controller.

    Figure 3. Adding the Controller

    Add Controller

  7. Open Controllers/ProductsController.cs.

  8. Update the GetProducts method as demonstrated by The following example.

    Example
        public DataSourceResult GetProducts([System.Web.Http.ModelBinding.ModelBinder(typeof(WebApiDataSourceRequestModelBinder))]DataSourceRequest request)
        {
            return db.Products.ToDataSourceResult(request);
        }
    
  9. Update the PostProduct method as demonstrated in The following example.

    Example
        public HttpResponseMessage PostProduct(Product product)
        {
            if (ModelState.IsValid)
            {
                db.Products.Add(product);
                db.SaveChanges();
    
                DataSourceResult result = new DataSourceResult
                {
                    Data = new[] { product },
                    Total = 1
                };
                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, result);
                response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = product.ProductID }));
                return response;
            }
            else
            {
                return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
            }
        }
    
  10. In the view, configure the Grid to use the Products Web API controller.

    Example
    
        <%: Html.Kendo().Grid<KendoGridWebApiCRUD.Models.Product>()
              .Name("grid")
              .Columns(columns =>
              {
                  columns.Bound(product => product.ProductID).Width(100);
                  columns.Bound(product => product.ProductName);
                  columns.Bound(product => product.UnitsInStock).Width(250);
                  columns.Command(commands =>
                  {
                      commands.Edit(); // The "edit" command will edit and update data items
                      commands.Destroy(); // The "destroy" command removes data items
                  }).Title("Commands").Width(200);
              })
              .ToolBar(toolbar => toolbar.Create()) // The "create" command adds new data items
              .Editable(editable => editable.Mode(GridEditMode.InLine)) // Use inline editing mode
              .DataSource(dataSource => dataSource
                    .WebApi()
                    .Model(model =>
                    {
                        model.Id(product => product.ProductID); // Specify the property which is the unique identifier of the model
                        model.Field(product => product.ProductID).Editable(false); // Make the ProductID property not editable
                    })
                    .Create(create => create.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "Products" }))) // Action invoked when the user saves a new data item
                    .Read(read => read.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "Products" }))) // Action invoked when the grid needs data
                    .Update(update => update.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "Products", id = "{0}" })))  // Action invoked when the user saves an updated data item
                    .Destroy(destroy => destroy.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "Products", id = "{0}" }))) // Action invoked when the user removes a data item
              )
              .Pageable()
        %>
    
    
        @(Html.Kendo().Grid<KendoGridWebApiCRUD.Models.Product>()
              .Name("grid")
              .Columns(columns =>
              {
                  columns.Bound(product => product.ProductID).Width(100);
                  columns.Bound(product => product.ProductName);
                  columns.Bound(product => product.UnitsInStock).Width(250);
                  columns.Command(commands =>
                  {
                      commands.Edit(); // The "edit" command will edit and update data items
                      commands.Destroy(); // The "destroy" command removes data items
                  }).Title("Commands").Width(200);
              })
              .ToolBar(toolbar => toolbar.Create()) // The "create" command adds new data items
              .Editable(editable => editable.Mode(GridEditMode.InLine)) // Use inline editing mode
              .DataSource(dataSource => dataSource
                    .WebApi()
                    .Model(model =>
                    {
                        model.Id(product => product.ProductID); // Specify the property which is the unique identifier of the model
                        model.Field(product => product.ProductID).Editable(false); // Make the ProductID property not editable
                    })
                    .Create(create => create.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "Products" }))) // Action invoked when the user saves a new data item
                    .Read(read => read.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "Products" }))) // Action invoked when the grid needs data
                    .Update(update => update.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "Products", id = "{0}" })))  // Action invoked when the user saves an updated data item
                    .Destroy(destroy => destroy.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "Products", id = "{0}" }))) // Action invoked when the user removes a data item
              )
              .Pageable()
        )
    
  11. Build and run the application.

    Figure 4. The final result

    Final result

See Also

Other articles on the Kendo UI Grid for ASP.NET MVC:

Articles on Telerik UI for ASP.NET MVC: