3 super easy steps to create a Kendo grid and integrate a drop down list in inline edit mode

Kendo dropdown inside Kendo grid MVC in 3 steps
25 April, 2017
Fady Soliman
8 Comments
46945 Views
 36 users marked as helpfull

Kendo dropdown inside Kendo grid MVC in 3 steps

This post will guide you through the following:

  1. Build a Kendo grid using the MVC razor wrappers
  2. Integrate an inline drow down list in an editable column
  3. Solve saving nullable model properties bound to drop down lists inside the Kendo grid on both create and edit events

Telerik Kendo Controls makes things pretty easy for both UX and UI developers as well as those who are using technologies such as ASP.NET MVC or other similar ones. This article is written how the Kendo drop down lists can be integrated in Kendo grids and used to advantage by programmers. Having Kendo grid drop down column in MVC is frequently used by web developers in the inline-editing mode of the grid.

You might also be interested in ASP.NET MVC DropdownLists where I explained in 3 steps how to create MVC DropDownLists with the least efforts using a simple data source, Razor helper and a single Bootstrap CSS class.


Note: This assumes that the person reading this post has a reasonable knowledge of ASP.NET MVC, Kendo UI (razor wrappers), as well as the related terminologies.

This article details in a step-by-step manner as to how to integrate the two options in a smooth manner using Kendo wrappers.

undefined

(Figure 1: Kendo dropdown list included in the Kendo grid)


Before we start: A quick video using Kendo grids in MVC

It might be useful to have a quick overview on how to build Kendo grids in MVC and compare them with traditional grids in ASP.NET to outline the differences and the out-of-the-box features granted when dealing with Kendo

Now lets move on to creating the Kendo grid with MVC code and how to add a dropdown list in inline editing mode in just 3 steps.


Unlimited free web design guest posts


Step 1 – Creating a Kendo UI Project (Optional)

Firstly, install Kendo UI on your development server in case you have not already done so. If you have not yet done so, go to Kendo Downloads and install the version of your choice. Soon after, a few project templates are installed by default by Kendo UI on Visual Studio. This can help you to create any project with ease that has Kendo UI integrated into it by default. Figure 2 displays some templates that are automatically installed by Kendo UI.

(Figure 2: Kendo UI – Project Templates Installed)


Step 2 – Creating A Kendo Grid

After creating a Kendo project (using the default templates of your choice) the next job is to use the Kendo grid MVC razor wrappers to create the views that are required in the project. The Kendo grid can be used thus using the following razor wrapper (relevant code is given below).

@(Html.Kendo().Grid<Employee>()
.Name("EmployeesGrid")
.Columns(columns =>
{
columns.Bound(e => e.FirstName).Title("First Name");
columns.Bound(e => e.LastName).Title("Last Name");
columns.Bound(e => e.CompanyId).EditorTemplateName("CompaniesList").Title("Company").ClientTemplate("#:CompanyName#");
columns.Command(command => { command.Edit(); });
})
.ToolBar(toolbar => toolbar.Create())
.Editable(editable => editable.Mode(GridEditMode.InLine))
.DataSource(dataSource => dataSource
.Ajax()
.Events(events => events.Error("error_handler"))
.Model(model => model.Id(e => e.Id))
.Create(update => update.Action("CreateEmployee", "Home"))
.Read(read => read.Action("ReadEmployees", "Home"))
.Update(update => update.Action("UpdateEmployees", "Home")))
)
<script type="text/javascript">
function error_handler(e) {
if (e.errors) {
var message = "Errors:\n";
$.each(e.errors, function (key, value) {
if ('errors' in value) {
$.each(value.errors, function() {
message += this + "\n";
});
}
});
alert(message);
}
}
</script>

Snippet 1: consists of a grid that contains the employee details such as the employee first name, employee last name, and name of the company. The definition of the Employee class follows:

public class Employee
{
public int Id { set; get; }
public string FirstName { set; get; }
public string LastName { set; get; }
public int CompanyId { set; get; }
public string CompanyName { set; get; }
}

Snippet 2: Employee class

This class of the following fields: employee id, employee first name, employee last name, company id and company name. These fields are named as in the code. The data corresponding to this code are gathered using any framework (how this is done is outside the premise of this article) from a data repository. The manner in which the data is to be presented is listed in the code that follows. However, it should be borne in mind that the field "CompanyName" should be retrieved for every employee. (The code listed below only serves as an example. You could replace this with your own code to get the job done.)

public List<Employee> GetAllEmployees()
{
List<Employee> employees = new List<Employee>();
employees.Add(new Employee() { Id = 1, FirstName = "John", LastName = "Smith", CompanyId = 1, CompanyName = "Microsoft" });
employees.Add(new Employee() { Id = 2, FirstName = "Tim", LastName = "Smith", CompanyId = 2, CompanyName = "UbiSoft" });
return employees;
}

Snippet 3: Employee data


Step 3 – Embedding the Kendo Drop-down List

The next step involves populating the Kendo drop-down list with the company names. This will help the user to select a company name from those that appear on a drop-down list when either Create mode or Edit mode is chosen. The user then chooses the company that the specific employee is associated with. The code that binds the column to CompanyId is shown below as point (1.). It can be seen in the Kendo MVC Grid creation step as well. Point (2.) explains how the code executes.

1. Ajax action that returns JsonResult and the dropdown binding in the grid

public JsonResult ReadEmployees([DataSourceRequest] DataSourceRequest request)
{
List<Employee> employess = GetAllEmployees();
DataSourceResult result = employess.ToDataSourceResult(request);
return Json(result, JsonRequestBehavior.AllowGet);
}

Snippet 4: The above snippet should be in the controller

columns.Bound(e => e.CompanyId).EditorTemplateName("CompaniesList").Title("Company").ClientTemplate("#:CompanyName#");

Snippet 5: The above snippet should be in Kendo grid in the view

2. The explanation for the above code is as follows:

The EditorTemplateName specifies to the grid that when either in Create or Edit modes, the template should be placed in the data file named "CompaniesList" that is found in the directory by name of EditorTemplates directory. The subsequent step therefore involves the creation of a folder by name of "EditorTemplates" and place an empty view in it by name of "CompaniesList". The code bit "ClientTemplate(“#:CompanyName#”)" means that when display is in the view mode, (that is, not creating or editing) CompanyName has to be displayed (in this case, it is "Microsoft"). Once this is complete, all what remains to be done is the creation of drop-down list which will be used in the view.


The data for the drop-down is sourced from ViewBag.Companies dynamic property. However, this has to be added to the code as shown below:

@using System.Collections
@model System.Int32

@(Html.Kendo().DropDownList()
.BindTo((IEnumerable)ViewBag.Companies)
.OptionLabel("- Select Company - ")
.DataValueField("Id")
.DataTextField("Name")
.Name("CompanyId")
)

Snippet 6: The drop down editor template

The above snippet should be in a separate view in "EditorTemplates" folder with the same name given to the EditorTemplateName in snippet 5 which is "CompaniesList"

Care should be taken while writing the code for creating the Kendo grid, the most important point being the statement Name(“CompanyId”). This name helper code statement should have exactly the same column name that the drop-down is bound to. In this specific example, the field to which column is bound to is "CompanyId" and this should be the name of the drop-down.

ViewBag.Companies = GetAllCompanies();

Snippet 7: drop down list data as companies

and the GetAllCompanies() method will be something like this. (You should replace this method with your own method)

public List<Company> GetAllCompanies()
{
List<Company> companies = new List<Company>();
companies.Add(new Company() { Id = 1, Name = "Microsoft" });
companies.Add(new Company() { Id = 2, Name = "UbiSoft" });
return companies;
}

Snippet 8: companies data

Nullable Model Properties – How to Take Care

If your model contains nullable properties of types integer, float or byte, it is not possible for the Kendo grid to update model properties to desired values during Create or Edit events. This can create bugs in the drop-downs. Therefore, if the field CompanyId is Nullable<int> instead of just int, then you may have to add code to save this event (to the grid) as follows:

.Events(events =>
{
events.Save("EmployeesGrid_Save");
})

Snippet 9: Kendo grid save event callback registration

Here, EmployeesGrid_Save will take care of the save event (JavaScript handler). The following save handler function will assist in saving the values of the drop-down to corresponding nullable properties.

function EmployeesGrid_Save(e) {
var companyId = $("#CompanyId").data().kendoDropDownList.value();
e.model.set("CompanyId", companyId);
}

Snippet 10: Kendo grid save event callback implementation


You are done

Now you have done everything, just build your project and check the Kendo MVC grid in inline mode, while creating or editing, with the Kendo drop down list integrated.

Related Posts

19 August, 2013
Fady Soliman
kendo ui , javascript
8 Comments
46945 Views

Did you find this helpfull?

About The Author

Fady Soliman

An experienced, resourceful and highly motivated IT professional, with a proven record of success in both Stack Development and Software Architecture. Possesses a wealth of transferable skills, including outstanding interpersonal, problem solving and staff management abilities. A capable organizer, quick to grasp – and make good use of – new ideas and information, and reliable and conscientious in all he takes on.

8 Responses

  1. pappu pager
    pappu pager10 November, 2013 12:08 PM(reply)
    I have a dropdown in a grid which has the product list and i want to display the product description as soon as you select the product from the dropdown. how can i achieve this.
  2. Fady Soliman
    Fady Soliman15 November, 2013 11:54 AM(reply)
    is this in the grid's edit mode or in display mode?
  3. George Nasim
    George Nasim25 December, 2013 11:17 AM(reply)
    how to get this event Events(events => { events.Save("EmployeesGrid_Save"); })
  4. Fady Soliman
    Fady Soliman02 January, 2014 01:45 AM(reply)
    it's one of the grid events like the error event in .Events(events => events.Error("error_handler")). You can just add the save event to the grid the same way like .Events(events => { events.Error("error_handler"); events.Save("save_handler"); })
  5. Thomas Jackson
    Thomas Jackson18 February, 2015 10:18 PM(reply)
    Thank you for that demonstration on creating the Employees list. I saw I could use that to add custom values to my model's properties, like when returning ones from a SQL view I did not want to update. I coverted the list using .ToDataSourceResult(), then sent that back in the "return Json(employees);" at the end of the update and it worked great. Thanks for the insight.
  6. Naga Rockie
    Naga Rockie14 March, 2016 06:30 AM(reply)
    If Company Id has to be made mandatory in kendo grid what i have to do i have added the below line but still i can add new row, changes other values and validation message is not thrown when i switch to other column: [Required(ErrorMessage = "CompanyName is required")] public int CompanyId { set; get; }
  7. Eric Hunt
    Eric Hunt08 November, 2016 07:24 AM(reply)
    Thank you so much for this article! The explanation of how to update a nullable int in the dropdown really helped me out a lot.
    • Fady Soliman
      Fady Soliman24 April, 2017 02:49 AM
      I know this is late but thank you and I'm glad it helped
  8. Michael Hagesfeld
    Michael Hagesfeld19 April, 2017 08:57 AM(reply)
    This seems excellent- but i cannot translate it to the HTML5/JQuery version of the grid/dropdown :( Do you have any advice for getting the dropdown value therein? Thanks, Mike
    • Fady Soliman
      Fady Soliman23 April, 2017 04:38 AM
      Thanks for your comment - Due to the huge requests to that topic I will be posting a new article about it and will modify this post to link to it in the "related posts" section and will reply to your comment again with the new post URL.

leave A Comment