Telerik Extensions for ASP.NET MVC

This help topic explains how to configure Telerik Grid for ASP.NET MVC to use Server editing.

Important

All Telerik UI components need a ScriptRegistrar component in order to output their JavaScript objects and register their JavaScript files. The ScriptRegistrar component should be defined *after* all other UI components in the page. If you create the components on the client-side and do not use the MVC extensions, you need to manually register all requried JavaScript files. For further information check this help topic (Step 4 - Register Scripts)

Important

The editing feature of Telerik Grid for ASP.NET MVC is available only for ASP.NET MVC 2.0 or later. Make sure you are using the right version of Telerik.Web.Mvc.Dll.

Server Editing (View)

To enable the editing support you must perform the following steps:
  1. Define a command column for the "Edit" and "Delete" commands:
    CopyC#
    <%= Html.Telerik().Grid(Model)
            .Name("Grid")
            .Columns(columns =>
            {
                //Bound columns
                columns.Bound(c => c.ContactName);
                columns.Bound(c => c.Country);
                columns.Bound(c => c.BirthDay);
                //Command column with two commands
                columns.Command(commands => commands
                       .Edit()
                       .Delete())
            })
    %>
  2. If you want to enable inserting of new records configure the grid toolbar:
    CopyC#
    <%= Html.Telerik().Grid(Model)
            .Name("Grid")
            // -> ToolBar configuration
            .ToolBar(commands => commands.Insert())
            // <- end of ToolBar configuration
            .Columns(columns =>
            {
                columns.Bound(c => c.ContactName);
                columns.Bound(c => c.Country);
                columns.Bound(c => c.BirthDay);
                columns.Command(commands => commands
                       .Edit()
                       .Delete())
            })
    %>
  3. Specify the property which uniquely identifies the data record. This is required so the grid knows which record is being edited, updated or deleted. In this case of this example this key is the CustomerID property:
    CopyC#
    <%= Html.Telerik().Grid(Model)
            .Name("Grid")
            // -> DataKeys configuration
            .DataKeys(dataKeys => dataKeys.Add(c => c.CustomerID))
            // <-- end of DataKeys configuration
            .ToolBar(commands => commands.Insert())
            .Columns(columns =>
            {
                columns.Bound(c => c.ContactName);
                columns.Bound(c => c.Country);
                columns.Bound(c => c.BirthDay);
                columns.Command(commands => commands
                       .Edit()
                       .Delete())
            })
    %>
  4. Specify the action methods which will delete, insert or update the data records:
    CopyC#
    <%= Html.Telerik().Grid(Model)
            .Name("Grid")
            .DataKeys(dataKeys => dataKeys.Add(c => c.CustomerID))
            .ToolBar(commands => commands.Insert())
            .DataBinding(dataBinding => dataBinding
                //Server binding
                .Server()
                    //Home.Index renders the grid initially
                    .Select("Index", "Home")
                    //Home.Insert inserts a new data record
                    .Insert("Insert", "Home")
                    //Home.Update updates an existing data record
                    .Update("Update", "Home")
                    //Home.Delete deletes an existing data record
                    .Delete("Delete", "Home")
            )
            .Columns(columns =>
            {
                columns.Bound(c => c.ContactName);
                columns.Bound(c => c.Country);
                columns.Bound(c => c.BirthDay);
                columns.Command(commands => commands
                       .Edit()
                       .Delete())
            })
    %>

Server Editing (Controller)

After configuring the grid in the view we need to implement the action methods which will bind the grid, insert, update and delete records. Let's assume there is a CustomerRepository class which retrieves data, inserts new records and updates and delete existing ones. The data object is Customer and is defined like this:
CopyCustomer
namespace Models
{
    using System;
    using System.ComponentModel.DataAnnotations;

    public class Customer
    {
        [Required]
        public string ContactName
        {
            get;
            set;
        }

        public string CustomerID
        {
            get;
            set;
        }

        [Required]
        public string Country
        {
            get;
            set;
        }

        [DataType(DataType.Date)]
        public DateTime BirthDay
        {
            get;
            set;
        }
    }
}
The Customer class is using the Required data annotation attribute which in turn is used for validation. Telerik Grid for ASP.NET MVC fully benefits from the validation support provided in ASP.NET MVC 2.
Note
The CustomerRepository is used just for brevity. In real-life it should be replaced with adequate repository implementation or other data access code (Linq to SQL, Entity Framework etc.)

Binding

To bind the grid we just need to render the view passing the data as model:
CopyC#
public ActionResult Index()
{
   //Render the view and pass all customer objects as the model
   return View(CustomerRepository.All());
}

Inserting

To insert a new record we need to create a new data object (Customer in this case) and use the TryUpdateModel to set its properties. TryUpdateModel will return false in case the model is not valid. Here is the code:
CopyC#
[HttpPost]                     
public ActionResult Insert()
{
  //Create a new instance of the Customer class.
  Customer customer = new Customer();

  //Perform model binding (fill the customer properties and validate it).
  if (TryUpdateModel(customer))
  {
     //The model is valid - insert the customer and redisplay the grid.
     CustomerRepository.Insert(customer);

     //GridRouteValues() is an extension method which returns the
     //route values defining the grid state - current page, sort expression, filter etc.
     return RedirectToAction("Index", this.GridRouteValues())
  }

  //The model is invalid - render the current view to show any validation errors.
  return View("Index", CustomerRepository.All());
}

Updating

To update an existing record we use the TryUpdateModel method again.
CopyC#
[HttpPost]
public ActionResult Update(string id)
{
    //Find a customer whose CustomerID is equal to the id action parameter
    Customer customer = CustomerRepository.FindById(id);

    if (customer == null)
    {
       //A customer with the specified id does not exist - redisplay the grid

       //GridRouteValues() is an extension method which returns the
       //route values defining the grid state - current page, sort expression, filter etc.
       return RedirectToAction("Index", this.GridRouteValues());
    }

    //Perform model binding (fill the customer properties and validate it).
    if (TryUpdateModel(customer))
    {
        //The model is valid - update the customer and redisplay the grid.
        CustomerRepository.Update(customer);

        //GridRouteValues() is an extension method which returns the 
        //route values defining the grid state - current page, sort expression, filter etc.
        return RedirectToAction("Index", this.GridRouteValues());
    }

    //The model is invalid - render the current view to show any validation errors
    return View("Index", SessionCustomerRepository.All());
}

Deleting

To delete an existing record we need to find that record, remove it from the repository and redisplay the grid:
CopyC#
[HttpPost]
public ActionResult Delete(string id)
{
    //Find the customer with the specified id
    Customer customer = CustomerRepository.FindById(id);

    if (customer == null)
    {
       //A customer with the specified id does not exist - redisplay the grid
       return RedirectToAction("Index", this.GridRouteValues());
    }

    //Delete the customer
    CustomerRepository.Delete(customer);

    //Redisplay the grid
    return RedirectToAction("Index", this.GridRouteValues());
}