# WebAPI Binding

Web API is an application programming interface that uses the [HTTP protocol](https://developer.mozilla.org/en-US/docs/Web/HTTP/Overview) for communication between clients and servers. For Grid scenarios, WebAPI binding connects CRUD transport operations to HTTP endpoints and returns data in a `DataSourceResult` shape.

For runnable examples, refer to the [demos on WebAPI binding of the Grid component](https://demos.telerik.com/aspnet-mvc/grid/webapi).

> important Defining a `Schema.Model.Id` is mandatory for proper execution of the Grid `Update`, `Create`, and `Destroy` operations.

## Setting Up the Application for WebAPI Binding

To ensure that the application is configured for both Web API binding capabilities:

1. Configure Web API by calling `GlobalConfiguration.Configure` in the `Application_Start` method.
   ```C#
         public class MvcApplication : System.Web.HttpApplication
         {
             protected void Application_Start()
             {
                 GlobalConfiguration.Configure(WebApiConfig.Register);
                 RouteConfig.RegisterRoutes(RouteTable.Routes);
             }
         }
   ```

2. Create a file named `WebApiConfig.cs` inside the `App_Start` folder and configure the default WebAPI routing convention.
   ```C#
       public static class WebApiConfig
       {
           public static void Register(HttpConfiguration config)
           {
               // Web API configuration and services.
               // Web API routes.
               config.MapHttpAttributeRoutes();
               config.Routes.MapHttpRoute(
                   name: "DefaultApi",
                   routeTemplate: "api/{controller}/{id}",
                   defaults: new { id = RouteParameter.Optional }
               );
           }
       }
   ```

## Adding a Web API Controller

To support reading and writing data through WebAPI endpoints, inherit the `ApiController` base class.

```C#
    public class ProductController : System.Web.Http.ApiController
    {
    }
```

## Configuring the CRUD Operations

1. Create a new ASP.NET MVC 5 application. If you have installed the [Telerik UI for ASP.NET MVC Visual Studio Extensions](https://www.telerik.com/aspnet-mvc/documentation/vs-integration/introduction), 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](https://www.telerik.com/aspnet-mvc/documentation/getting-started-mvc/first-steps) 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**.

   ![UI for ASP.NET MVC A new entity data model](https://www.telerik.com/aspnet-mvc/documentation/assets/1286540ae776a0b9803b365ff9a0c775/grid-entity-data-model.png)

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.
   ![UI for ASP.NET MVC Choosing the Products table in the database objects](https://www.telerik.com/aspnet-mvc/documentation/assets/9b3c6e48269198e2986c090f51010f6a/grid-binding-choose-database-objects.png)

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

6. Set **ProductController** 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 WebAPI controller.

   ![UI for ASP.NET MVC Adding the Controller](https://www.telerik.com/aspnet-mvc/documentation/assets/1db4d3e95da8c7dda9f688354b1d63c8/grid-api-controller.png)

7. Update the `Get` method as demonstrated in the following example.

   ```C#
       public DataSourceResult Get([System.Web.Http.ModelBinding.ModelBinder(typeof(WebApiDataSourceRequestModelBinder))]DataSourceRequest request)
       {
           return db.Products.ToDataSourceResult(request);
       }
   ```

8. Update the `Post` method as demonstrated in the following example.

   ```C#
        public HttpResponseMessage Post(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);
            }
        }
   ```

9. Update the `Put` method as demonstrated in the following example.

   ```C#
       public HttpResponseMessage Put(int id, ProductViewModel product)
       {
           if (ModelState.IsValid && id == product.ProductID)
           {
               try
               {
                   service.Update(product);
               }
               catch (DbUpdateConcurrencyException)
               {
                   return Request.CreateResponse(HttpStatusCode.NotFound);
               }

               return Request.CreateResponse(HttpStatusCode.OK);
           }
           else
           {
               var errors = ModelState.Values.SelectMany(v => v.Errors).Select(error => error.ErrorMessage);
               return Request.CreateResponse(HttpStatusCode.BadRequest, errors);
           }
       }
   ```

10. Update the `Delete` method as demonstrated in the following example.

    ```C#
        public HttpResponseMessage Delete(int id)
        {
            ProductViewModel product = service.Read().FirstOrDefault(p => p.ProductID == id);

            if (product == null)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            try
            {
                service.Destroy(product);
            }
            catch (DbUpdateConcurrencyException)
            {
                return Request.CreateResponse(HttpStatusCode.NotFound);
            }

            return Request.CreateResponse(HttpStatusCode.OK, product);
        }
    ```

11. In the view, configure the Grid to use the Products WebAPI controller.

```Razor HtmlHelper
    @(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 edit 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.
            })
            
            .Read(read => read.Url(Url.HttpRouteUrl("DefaultApi", new { controller = "Product" }    )))
            .Create(create => create.Url(Url.HttpRouteUrl("DefaultApi", new { controller =  "Product" })))
            .Update(update => update.Url(Url.HttpRouteUrl("DefaultApi", new { controller =  "Product", id = "{0}" })))
            .Destroy(destroy => destroy.Url(Url.HttpRouteUrl("DefaultApi", new { controller =   "Product", id = "{0}" })))
            
        )
    )
```

## Building the application

The final result is a Grid with configured editing.

![UI for ASP.NET MVC Grid with inline editing configured after WebAPI binding setup](https://www.telerik.com/aspnet-mvc/documentation/assets/b67de688702741c5fb57ccf74a754b48/grid-inline-editing.png)

## See Also

* [WebApi Binding for the Grid HtmlHelper for Telerik UI for ASP.NET MVC (Demos)](https://demos.telerik.com/aspnet-mvc/grid/webapi)
* [Server-Side API](https://www.telerik.com/aspnet-mvc/documentation/api/grid)
