# Server Binding

By default, the Telerik UI Grid for ASP.NET MVC sends `HTTP GET` requests to the server for paging, sorting, and filtering operations.

## Supported Client-Side Events

The Grid supports the following client-side events when it is in server binding mode:

* `Change`
* `ColumnHide`
* `ColumnMenuInit`
* `ColumnReorder`
* `ColumnResize`
* `ColumnShow`
* `DetailCollapse`
* `DetailExpand`
* `ExcelExport`
* `FilterMenuInit`
* `PdfExport`
* `GroupExpand`—The group object that is associated with group row will be empty in server binding scenario.
* `GroupCollapse`—The group object that is associated with group row will be empty in server binding scenario.

> important
>
> * Client-side events related to data binding and CRUD operations are not raised when the Grid is configured for server binding.
> * Locked columns are not supported. To use locked columns, use [Ajax binding](https://www.telerik.com/aspnet-mvc/documentation/html-helpers/data-management/grid/binding/ajax-binding).
> * Showing or hiding columns and reordering with `GroupHeaderColumnTemplate` in server-binding scenarios is not supported. In server-binding scenarios, the Kendo UI for jQuery DataSource instance does not include group and aggregate information, so group-row templates cannot be compiled on the client.
> * Row spanning is not supported. To use row and column spanning, use [Ajax binding](https://www.telerik.com/aspnet-mvc/documentation/html-helpers/data-management/grid/binding/ajax-binding) and review [Row and Column Spanning](https://www.telerik.com/aspnet-mvc/documentation/html-helpers/data-management/grid/row-column-spanning).

## Getting Started

To bind the Grid to data, set its data source and render the view by using any of the following approaches:

* [Bind to the view model](https://www.telerik.com/aspnet-mvc/documentation/html-helpers/data-management/grid/binding/server-binding#binding-to-the-view-model)
* [Bind to items from `ViewData` or `ViewBag`](https://www.telerik.com/aspnet-mvc/documentation/html-helpers/data-management/grid/binding/server-binding#using-the-viewdata-or-viewbag-items-binding)
* [Use the `BindTo` method](https://www.telerik.com/aspnet-mvc/documentation/html-helpers/data-management/grid/binding/server-binding#applying-the-bindto-method)
* [Pass additional data to an action method](https://www.telerik.com/aspnet-mvc/documentation/html-helpers/data-management/grid/binding/server-binding#passing-additional-data-to-action-methods)

## Binding to the View Model

The example below demonstrates how to bind the Grid to a model.

```C# Controller
    public ActionResult Index()
    {
        var northwind = new NorthwindEntities();
        var products = northwind.Products;
        return View(products);
    }
```

```Razor
    @model IEnumerable<KendoGridServerBinding.Models.Product>

    @(Html.Kendo().Grid(Model) //Bind the Grid to the Model property of the view.
        .Name("Grid")
        .Columns(columns =>
        {
            columns.Bound(p => p.ProductID);   // Create a column bound to the "ProductID" property
            columns.Bound(p => p.ProductName); // Create a column bound to the "ProductName" property
            columns.Bound(p => p.UnitPrice);   // Create a column bound to the "UnitPrice" property
            columns.Bound(p => p.UnitsInStock);// Create a column bound to the "UnitsInStock" property
        })
        .Pageable() //Enable paging.
    )
```

## Using the ViewData or ViewBag Items Binding

The following example demonstrates how to apply data binding with `ViewData` or `ViewBag`.

```C# Controller
    public ActionResult Index()
    {
        var products = new NorthwindDataContext().Products;

        ViewData["products"] = products;

        return View();
    }
```

```Razor
    @(Html.Kendo().Grid((IEnumerable<MvcApplication1.Models.Product>)ViewData["products"])
        .Name("Grid")
        .Columns(columns =>
        {
            columns.Bound(p => p.ProductID);
            columns.Bound(p => p.ProductName);
            columns.Bound(p => p.UnitPrice);
            columns.Bound(p => p.UnitsInStock);
        })
    )
```

## Applying the BindTo Method

The following example demonstrates how to bind the Grid to data by using the `BindTo` method.

```C# Controller
    public ActionResult Index()
    {
        var products = new NorthwindDataContext().Products;

        ViewBag.Products = products;

        return View();
    }
```

```Razor
    @(Html.Kendo().Grid<MvcApplication1.Models.Product>() // Specify the type of the grid
        .Name("Grid")
        .BindTo((IEnumerable<MvcApplication1.Models.Product>)ViewBag.Products)
        .Columns(columns =>
        {
            columns.Bound(p => p.ProductID);
            columns.Bound(p => p.ProductName);
            columns.Bound(p => p.UnitPrice);
            columns.Bound(p => p.UnitsInStock);
        })
    )
```

The Grid makes `HTTP GET` requests to the action method that initially renders the view. The Grid page, sort, filter, and group information is passed as query string parameters.

For example, a server-bound Grid URL can look like `http://localhost:4939/?Grid-sort=ProductName-asc&Grid-page=2`. The Grid `Name` is used as a query-string prefix so multiple server-bound Grid instances can coexist in the same view. You can disable the prefix through the `PrefixUrlParameters` method.

```Razor HtmlHelper
<%: Html.Kendo().Grid(Model)
    .Name("Grid")
    .PrefixUrlParameters(false)
%>
```

## Passing Additional Data to Action Methods

The action method that renders the view containing the Grid may need additional data.

```C# Controller
    public ActionResult Index(string firstName, string lastName)
    {
        var products = new NorthwindDataContext().Products;

        return View(products);
    }
```

```Razor
    @(Html.Kendo().Grid(Model)
        .Name("Grid")
        .DataSource(dataSource => dataSource
            .Server() // Specify server type
            .Read(read => read.Action("Index", "Home", new { firstName = "John", lastName = "Doe" }))
        )
    )
```

## Setting Up the Sample Project

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 application. Name the application `KendoGridServerBinding`. 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. Pick the **EF Designer from database** option and click **Next**. Configure a connection to the Northwind database. Click **Next**.

   ![UI for ASP.NET MVC Choosing the connection](https://www.telerik.com/aspnet-mvc/documentation/assets/1b29022c17fddc909b4d7bd3de4fbdce/grid-binding-choose-data-connection.png)

4. Choose the **Products** table from the `Which database objects do you want to include in your model?`. Leave all other options as they are set by default. Click **Finish**.

   ![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. Open **HomeController.cs** and modify the `Index` action method.

   ```C#
   public ActionResult Index()
   {
       ViewBag.Message = "Welcome to ASP.NET MVC!";
       var northwind = new NorthwindEntities();
       // Get the Products entities and add them to the ViewBag.
       ViewBag.Products = northwind.Products;
       return View();
   }
   ```

6. Modify the `Create` method as demonstrated in the following example.

   ```C#
   [AcceptVerbs(HttpVerbs.Post)]
   public ActionResult Create(Product product)
   {
       if (ModelState.IsValid)
       {
           productService.Create(product);

           RouteValueDictionary routeValues = this.GridRouteValues();

           return RedirectToAction("Index", routeValues);
       }

       return View("Index", productService.GetAll());
   }
   ```

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

   ```C#
   [AcceptVerbs(HttpVerbs.Post)]
   public ActionResult Update(Product product)
   {
       if (ModelState.IsValid)
       {
           productService.Update(product);

           RouteValueDictionary routeValues = this.GridRouteValues();

           return RedirectToAction("Index", routeValues);
       }

       return View("Index", productService.GetAll());
   }
   ```

8. Modify the `Destroy` method as demonstrated in the following example.

   ```C#
   [AcceptVerbs(HttpVerbs.Post)]
   public ActionResult Destroy(int productID)
   {
       Product product = productService.GetAll().FirstOrDefault(p => p.ProductID == productID);

       RouteValueDictionary routeValues;

       if (product == null)
       {
           routeValues = this.GridRouteValues();

           return RedirectToAction("Index", routeValues);
       }

       productService.Destroy(product);

       routeValues = this.GridRouteValues();

       return RedirectToAction("Index", routeValues);
   }
   ```

9. Add a Kendo UI Grid to the `Index` view.

   ```Razor
       @(Html.Kendo().Grid((IEnumerable<KendoGridServerBinding.Models.Product>)ViewBag.Products) //Bind the grid to ViewBag.Products
           .Name("grid")
           .Columns(columns =>
           {
               columns.Bound(product => product.ProductID);
               columns.Bound(product => product.ProductName);
               columns.Bound(product => product.UnitsInStock);
               columns.Bound(product => product.Discontinued);
               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(300);
           })
           .ToolBar(commands => commands.Create())
           .Pageable() //Enable the paging.
           .Sortable() //Enable the sorting.
           .DataSource(dataSource => dataSource
               .Server()
               // Specify that the ProductID property is the unique identifier of the model.
               .Model(model => model.Id(p => p.ProductID))
               .Create(create => create.Action("Create", "Home"))
               .Update(update => update.Action("Update", "Home"))
               .Destroy(destroy => destroy.Action("Destroy", "Home"))
           )
       )
   ```

10. Build and run the application.

    ![UI for ASP.NET MVC The final result is a Grid bound to data](https://www.telerik.com/aspnet-mvc/documentation/assets/647f39983cf24872e875e04b8edcc8bb/grid-bound-data.png)

## See Also

* [Binding the Grid HtmlHelper for ASP.NET MVC to Data (Demos)](https://demos.telerik.com/aspnet-mvc/grid/local-data-binding)
* [Ajax Binding by the Grid HtmlHelper for ASP.NET MVC](https://www.telerik.com/aspnet-mvc/documentation/html-helpers/data-management/grid/binding/ajax-binding)
* [Server-Side API](https://www.telerik.com/aspnet-mvc/documentation/api/grid)
