# OData-v4 Binding

[OData (Open Data Protocol)](https://www.odata.org/) defines best practices for building and consuming RESTful APIs. It provides built-in support for filtering, selecting, and expanding, among other query capabilities. By binding the ASP.NET MVC Grid to OData-v4, you can extend your REST API with advanced query options.

For a runnable example, refer to the [Grid OData-v4 binding demo](https://demos.telerik.com/aspnet-mvc/grid/odatav4).

## Installing the OData Package

Install the required OData dependencies by adding the `Microsoft.AspNet.OData` and `Microsoft.AspNet.WebApi.WebHost` NuGet packages to your project.

## Building the EDM Model and Configuring OData in an ASP.NET MVC Environment

To configure the application for both Web API and OData binding:

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` in the `App_Start` folder, and configure the EDM model and OData services.

```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 }
          );

          var builder = new ODataConventionModelBuilder();
          builder.EntitySet<Product>("Products");

          config.Count().Filter().OrderBy().Expand().Select().MaxTop(null);
          config.MapODataServiceRoute("odata", "odata", builder.GetEdmModel());
      }
  }
```

## Adding an OData Controller

To support read and write operations in OData format, inherit from the `ODataController` base class.

```C#
    public class ProductsController : ODataController
    {
        ...
    }
```

Then, decorate the REST API endpoints with the `EnableQuery` attribute so the query options from the URL are applied automatically.

```C#
    public class ProductsController : ODataController
    {
        [EnableQuery]
        public List<Product> GetProducts()
        {
            var products = GetProducts(); // Call to the database.
            return products;
        }

        [EnableQuery]
        public IHttpActionResult Put([FromODataUri] int key, [FromBody] Product product)
        {
            // Custom update logic and update the Category field.
            return Updated(product);
        }
        [EnableQuery]
        public IHttpActionResult Post([FromBody] Product product)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            // Custom create logic and update the Category field.
            return Created(product);
        }
        public IHttpActionResult Delete([FromODataUri] int key)
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            // Custom delete logic.
            return StatusCode(HttpStatusCode.NoContent);
        }
    }
```

## Configuring the Grid for OData-v4 Binding

To bind the Telerik UI for ASP.NET MVC Grid to OData-v4, set `.Type("odata-v4")` in the DataSource configuration. This setting sends requests to the OData endpoint in the expected format.

```Razor HtmlHelper
    @(Html.Kendo().Grid<Product>()
         .Name("grid")
         .Columns(columns =>
         {
             columns.Bound(p => p.ProductName);
             columns.Bound(p => p.UnitsInStock);
             columns.Bound(p => p.Discontinued);
             columns.Bound(p => p.UnitsOnOrder);
             columns.Bound(p => p.UnitPrice).Width(150);
         })
         .Pageable()
         .DataSource(dataSource => dataSource
             .Custom()
             .Type("odata-v4")
             .Schema(schema => schema
             .Model(model =>
             {
                 model.Id(t => t.ProductID);
                 model.Field(t => t.ProductID).Editable(false);
                 model.Field(t => t.ProductName);
                 model.Field(t => t.UnitPrice);
                 model.Field(t => t.UnitsInStock);
                 model.Field(t => t.UnitsOnOrder);
                 model.Field(t => t.Discontinued);
             }))
             .Transport(transport =>
             {
                 transport.Read(read => read.Url("/odata/Products"));
             })
             .PageSize(10)
             .ServerPaging(true)
         )
    )
```

## Configuring the CRUD Operations

To configure CRUD operations for OData-v4 binding, add `ClientHandlerDescriptor` handlers that map each request to the corresponding OData-v4 endpoint.

```Razor HtmlHelper
  @(Html.Kendo().Grid<Product>()
      .Name("grid")
      .Columns(columns =>
      {
          columns.Bound(p => p.ProductName);
          columns.Bound(p => p.UnitsInStock);
          columns.Bound(p => p.Discontinued);
          columns.Bound(p => p.UnitsOnOrder);
          columns.Bound(p => p.UnitPrice).Width(150);
          columns.Command(c => {c.Edit(); c.Destroy();}).Width(150);
      })
      .Toolbar(toolbar => toolbar.Create())
      .Pageable()
      .Editable(editable => editable.Mode(GridEditMode.InLine))
      .DataSource(dataSource => dataSource
          .Custom()
          .Type("odata-v4")
          .Schema(schema => schema
          .Model(model =>
          {
              model.Id(t => t.ProductID);
              model.Field(t => t.ProductID).Editable(false);
              model.Field(t => t.ProductName);
              model.Field(t => t.UnitPrice);
              model.Field(t => t.UnitsInStock);
              model.Field(t => t.UnitsOnOrder);
              model.Field(t => t.Discontinued);
          }))
          .Transport(transport =>
          {
              transport.Read(read => read.Url("/odata/Products"));
              transport.Update(new { url = new Kendo.Mvc.ClientHandlerDescriptor() { HandlerName = "update" } });
              transport.Destroy(new { url = new Kendo.Mvc.ClientHandlerDescriptor() { HandlerName = "destroy" } });
              transport.Create(new { url = new Kendo.Mvc.ClientHandlerDescriptor() { HandlerName = "create" } });
          })
          .PageSize(10)
          .ServerPaging(true)
      )
    )

    <script>
        function update(dataItem){
            return "/odata/Products(" + dataItem.ProductID + ")"
        }
        function create(){
            return "/odata/Products"
        }
        function destroy(dataItem){
            return "/odata/Products(" + dataItem.ProductID + ")"
        }
    </script>
```

## Configuring Batch Editing

To enable batch editing in an ASP.NET MVC environment:

1. Add a default batch handler inside the `WebApiConfig` file.

```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 }
          );

          var builder = new ODataConventionModelBuilder();
          builder.EntitySet<Product>("Products");

          config.Count().Filter().OrderBy().Expand().Select().MaxTop(null);
          config.MapODataServiceRoute("odata", "odata", new DefaultODataBatchHandler(GlobalConfiguration.DefaultServer));
      }
  }
```

2. In the Grid, configure the batch operation with `ClientHandlerDescriptor`, and enable the DataSource `Batch()` option.

```Razor HtmlHelper
    @(Html.Kendo().Grid<ProductViewModel>()
        .Name("grid")
         .Columns(columns =>
            {
                columns.Bound(p => p.ProductName);
                columns.Bound(p => p.QuantityPerUnit);
                columns.Bound(p => p.UnitsInStock);
                columns.Bound(p => p.Discontinued);
                columns.Bound(p => p.UnitsOnOrder);
                columns.Bound(p => p.UnitPrice).Width(150);
                columns.Command(command => command.Destroy()).Width(150);
            })
            .ToolBar(toolBar =>
            {
                toolBar.Create();
                toolBar.Save();
            })
            .Editable(editable => editable.Mode(GridEditMode.InCell))
            .Pageable()
            .Sortable()
            .Scrollable()
            .HtmlAttributes(new { style = "height:550px;" })
            .DataSource(dataSource => dataSource
            .Custom()
            .Batch(true)
            .Type("odata-v4")
            .Schema(schema => schema
            .Model(m =>
            {
                m.Id(t => t.ProductID);
                m.Field(t => t.ProductID).Editable(false);
                m.Field(t => t.ProductName);
                m.Field(t => t.QuantityPerUnit);
                m.Field(t => t.UnitPrice);
                m.Field(t => t.UnitsInStock);
                m.Field(t => t.UnitsOnOrder);
                m.Field(t => t.Discontinued);
            }))
            .Transport(t =>
            {
                t.Read(read => read.Url("/odata/Products"));
                t.Update(new { url = new Kendo.Mvc.ClientHandlerDescriptor() { HandlerName = "update" } });
                t.Destroy(new { url = new Kendo.Mvc.ClientHandlerDescriptor() { HandlerName = "destroy" } });
                t.Create(new { url = new Kendo.Mvc.ClientHandlerDescriptor() { HandlerName = "create" } });
                t.Batch(new { url = new Kendo.Mvc.ClientHandlerDescriptor() { HandlerName = "batch" } });
            })
            .PageSize(10)
            .ServerPaging(true)
         )
    )
    <script>
        function batch(){
            return "/odata/$batch"
        }
        function update(dataItem){
            return "/odata/Products(" + dataItem.ProductID + ")"
        }
        function create(){
            return "/odata/Products"
        }
        function destroy(dataItem){
             return "/odata/Products(" + dataItem.ProductID + ")"
        }
    </script>
```

## See Also

* [OData-v4 Binding by the Grid HtmlHelper for ASP.NET MVC (Demo)](https://demos.telerik.com/aspnet-mvc/grid/odata)

* [Official Microsoft Documentation on Getting Started with ASP.NET MVC OData-v4](https://learn.microsoft.com/en-us/aspnet/web-api/overview/odata-support-in-aspnet-web-api/odata-v4/create-an-odata-v4-endpoint)

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