# 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-core/grid/webapi).

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

## Adding a Web API Controller

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

```C#
    [ApiController()]
    [Route("api/[controller]")]
    public class ProductController : BaseController
    {
    }
```

## Configuring the CRUD Operations

1. Add a new class to the `~/Models` folder. The following example uses the `ProductViewModel` name.
   ```C#
       public class ProductViewModel
       {
           public int ProductID { get; set; }
           // The ProductName property is required.
           [Required]
           public string ProductName { get; set; }
           // Use the Integer editor template for the UnitsInStock property.
           [UIHint("Integer")]
           public short? UnitsInStock { get; set; }
       }
   ```

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

   ```C#
       [HttpGet]
       public DataSourceResult Get([DataSourceRequest]DataSourceRequest request)
       {
           return db.Products.ToDataSourceResult(request);
       }
   ```

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

   ```C#
        [HttpPost]
        public IActionResult Post([FromForm] ProductViewModel product)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState.Values.SelectMany(v => v.Errors).Select(error => error.ErrorMessage));
            }

            service.Create(product);

            return new ObjectResult(new DataSourceResult { Data = new[] { product }, Total = 1 });
        }
   ```

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

   ```C#
       [HttpPut("{id}")]
       public IActionResult Put(int id, [FromForm] ProductViewModel product)
       {
           if (ModelState.IsValid && id == product.ProductID)
           {
               try
               {
                   service.Update(product);
               }
               catch (DbUpdateConcurrencyException)
               {
                   return new NotFoundResult();
               }

               return new StatusCodeResult(200);
           }

           return BadRequest(ModelState.Values.SelectMany(v => v.Errors).Select(error => error.ErrorMessage));
       }
   ```

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

   ```C#
       [HttpDelete("{id}")]
       public IActionResult Delete(int id)
       {
           try
           {
               service.Destroy(new ProductViewModel { ProductID = id } );
           }
           catch (DbUpdateConcurrencyException)
           {
               return new NotFoundResult();
           }
           return new StatusCodeResult(200);
       }
   ```

6. 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.Action("Get", "Product"))
            .Create(create => create.Action("Post", "Product"))
            .Update(update => update.Action("Put", "Product", new { id = "{0}"} ))
            .Destroy(destroy => destroy.Action("Delete", "Product", new { id = "{0}" }))
            
        )
    )
```

```Razor TagHelper
@{  var Id = new { id = "{0}" }; }

<kendo-grid name="grid" height="430">
    <columns>
        <column field="ProductID" />
        <column field="ProductName" />
        <column field="UnitsInStock" />
        <column title="Commands" width="200">
            <commands>
                <column-command text="Edit" name="edit"></column-command>
                <column-command text="Delete" name="destroy"></column-command>
            </commands>
        </column>
    </columns>
    <toolbar>
        <toolbar-button name="create"></toolbar-button>
    </toolbar>
    <editable mode="inline" />
    <datasource type="DataSourceTagHelperType.WebApi">
        <schema>
            <model id="ProductID">
                <fields>
                    <field name="ProductID" editable="false"></field>
                </fields>
            </model>
        </schema>
        <transport>
            <read url="@Url.Action("Get", "Product")"/>
            <create url="@Url.Action("Post", "Product")"/>
            <update url="@Url.Action("Put", "Product")" data ="@Id"/>
            <destroy url="@Url.Action("Delete", "Product")" data="@Id"/>
        </transport>
    </datasource>
</kendo-grid>
```

## Building the application

The final result is a Grid with configured editing.

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

## See Also

* [ASP.NET Core DataGrid Homepage](https://www.telerik.com/aspnet-core-ui/grid)

* [WebApi Binding for the Grid HtmlHelper for Telerik UI for ASP.NET Core (Demos)](https://demos.telerik.com/aspnet-core/grid/webapi)

* [Server-Side API](https://www.telerik.com/aspnet-core-ui/documentation/api/grid)
