Kendo DropDownList Wrapper for ASP.NET MVC

Overview:

This is the sixth post in the series on Kendo UI wrappers for ASP.NET MVC. We will look at one more wrapper in this post namely DropDownList. This post is part of a getting started with Kendo UI wrappers for ASP.NET MVC and you can find the index post here.

What is DropDownList Wrapper?

First lets understand what is a DropDownList control. A DropDownList displays a list of values and allows the selection of a single value from the list. Custom values are not allowed i.e. user cannot type in a custom value rather he can only select from the list.

image

The DropDownList Wrapper for ASP.NET MVC is a server side wrapper for Kendo UI DropDownList which is a JavaScript based widget.

Basic Usage:

In order to instantiate a DropDownList wrapper on any webpage, we make use of the DropDownList extension available within the Kendo helpers. Here is the code which will create a DropDownList control:

 
@( Html.Kendo().DropDownList().Name("kdropdownlist") ) 

Here is the output of the above code:

image

The Name is a required setting on the control. Without that setting we will get error, so provide a unique name every time you instantiate the drop down list control.

Data Binding Scenarios:

The data binding options available for drop down list wrapper are Server binding and Ajax binding. We will look at them one by one.

Server Data Binding:

Lets start by creating an action method. We will build a static list of SelectListItem and pass it as the Model to the view. Here is the code to illustrate that:

 
public ActionResult DropDownList() 
{ 
var items = new List() 
{ 
new SelectListItem { Value="1", Text="Beverages" }, 
new SelectListItem { Value="2", Text="Condiments" }, 
new SelectListItem { Value="3", Text="Confectionries" }, 
new SelectListItem { Value="4", Text="Dairy" }
}; 
return View(items); 
} 

Next we will see how we bind the model data to the drop down list wrapper. Here is the Razor view code:

 
@model List<SelectListItem> 
@( 
   Html.Kendo().DropDownList().Name("kdropdownlist") 
               .DataTextField("Text") 
               .DataValueField("Value") 
               .BindTo(Model) 
               .OptionLabel("Select a category") 
) 

As you can see we first let the view know what is the model type it will be working with i.e. the view is now strongly typed. In this case we have a List<SelecteListItem>. Then we use the BindTo() method of the drop down list helper to bind the control with data. We also need to set what is the Text field and Value field to bind too within the model. Now if we run this code, following is result we get:

image

Notice the use of OptionsLabel() method. This lets you add a empty item before any of the data items from the model. So this is like a placeholder or a cue to the user as to what he needs to do.

Ajax Data Binding:

In this section we will see how to bind the drop down list using an Ajax call. First lets create an action method which returns JsonResult instead of ActionResult. The action method will convert the category list which we saw in the server binding as a Json object and return it. Here is the code to illustrate the action method:

 
public JsonResult GetCategories() 
{ 
   var items = new List() 
   { 
      new SelectListItem { Value="1", Text="Beverages" }, 
      new SelectListItem { Value="2", Text="Condiments" }, 
      new SelectListItem { Value="3", Text="Confectionries" }, 
      new SelectListItem { Value="4", Text="Dairy" } 
   }; 
    return Json(items, JsonRequestBehavior.AllowGet); 
} 

We just create the data as we would prepare and then use the Json() method to convert the objects to Json format and return that. Now we will see how to make AJAX call to bind the drop down list with data. Here is the code for the same:

 
@( 
   Html.Kendo().DropDownList() 
               .Name("kdropdownlistajax") 
               .DataTextField("Text") 
               .DataValueField("Value") 
               .DataSource(source => 
               { 
                 source.Read(read => { read.Action("GetCategoriesAjax", "Home"); }); 
               }) 
               .OptionLabel("Select a category") 
) 

Instead of using the BindTo() method, we make use of DataSource() method. Within the datasource method we set the read action i.e. what is the action on a controller which will provide us the Json data. With this setting we are not binding the data at the server side, rather the data is bound on the client side.

You will not find any difference when you run the application. But when you do the network sniffing you will see that the control issues a AJAX call to the action method configured for read purpose. Here is a screen shot of the network activity of the page:

SNAGHTML3df1d34a

So we saw how we can use either the server side data binding or client side data binding through AJAX. Depending on your scenario you can take any of the approaches.

Customizing Item Templates:

In the above sections we saw that the Items of the drop down list were just shown as text. With Kendo DropDownList it is possible to customize item templates. The item templates will be visible when the drop down list is in open state. When it is in collapsed state the drop down list will just show the  text field that is bound to the data object. In our example lets say we have images for each of the category and when the drop down list is open we would like to show image next to each of the category name. We can do that easily my making use of the Template() method. You can provide any HTML template and customize each item appearance. Since the templates are pure HTML, Kendo provides a special syntax to access the properties on the bound data object. The syntax is ${<PropertyName>}. That’s it and you can refer the properties of the data item within your custom templates. Here is the code which illustrates the custom teamplate implementation:

 
@( 
   Html.Kendo().DropDownList() 
               .Name("kdropdownlist") 
               .DataTextField("Text") 
               .DataValueField("Value") 
               .BindTo(Model) 
               .Template("<img alt='' src='" + Url.Content("~/Images/") + "${Text}.gif' width='40' height='40' />" + 
                         "<span style='padding: 10px;'>${Text}</span>") 
) 

The template is self explanatory. We have image tag whose source is set to an image url formed by using the text of the item itself and then we are showing the text as is. This is a simple template, but the power of template allows you to customize the UI to your needs.

Cascading DropDownList:

One of the common scenarios on web is to cascade a dropdownlist based on a value selected in another dropdownlist. For e.g. I want to show categories dropdown and products dropdowb but the products dropdown should not be enabled until user selects a value in category dropdown. Once a category is selected the products dropdown should get enabled and display all products belonging to that category. With Kendo DropDownList this can be achieved very easily. For the purpose of this example, we will created one more action method GetProductsAjax() which accepts a categoryid and will return products based on the category selected from this action. Here is the code for the same:

 
public JsonResult GetProductsAjax(string categoryId) 
{ 
   var items = new List() 
   { 
      new SelectListItem { Value=categoryId + "1", Text="Product 1" + categoryId }, 
      new SelectListItem { Value=categoryId + "2", Text="Product 2" + categoryId }, 
      new SelectListItem { Value=categoryId + "3", Text="Product 3" + categoryId }, 
      new SelectListItem { Value=categoryId + "4", Text="Product 4" + categoryId } 
   }; 
   return Json(items, JsonRequestBehavior.AllowGet); 
} 

I am just building a static list of products for the demo purpose.

next we will see how we can cascade a product dropdownlist based on category dropdownlist. We will place 2 dropdownlist on the screen – one for category and another for product. Here is the view code:

Category DropDownList:

 
@(
   Html.Kendo().DropDownList() 
               .Name("categories") 
               .OptionLabel("Select category...") 
               .DataTextField("Text") 
               .DataValueField("Value") 
               .DataSource(source => 
                          { source.Read(read => { read.Action("GetCategoriesAjax", "Home"); }); }
                          ) 
) 

Products DropDownList:

 
@(
   Html.Kendo().DropDownList() 
               .Name("products") 
               .OptionLabel("Select product...") 
               .DataTextField("Text") 
               .DataValueField("Value") 
               .DataSource(source => 
                          { 
                             source.Read(read => { read.Action("GetProductsAjax", "Home") 
                                   .Data("filterProducts"); 
                          }) 
               .ServerFiltering(true); }) 
               .Enable(false) 
               .AutoBind(false) 
               .CascadeFrom("categories") 
)
<script>
   function filterProducts() 
   {
      return {categoryId: $("#categories").val()};
   }
</script>

Notice couple of things in products drop down list. Firstly, in the data source read, we use a Data() method to pass additional data for the request. In this case, we invoke a javascript function which extracts the value of the selected category and pass it to the request. Then we set a property on the drop down list called AutoBind() which controls if the control should fetch the data on load of the control. In our case since we need to wait till a category is selected, we set auto bind to false. Lastly we set a property called CascadeFrom() and pass the parent drop down list id. This property takes care of keeping the products drop down in sync with the category selected. This will also control the enabling and disabling of product drop down based on whether a value is selected in category drop down or not. Here is the out put of the above code:

image

Handling Events:

DropDownList exposes 4 main events on the client side. You can subscribe to those events and perform your business logic if any. The event exposed are as follows:

  • Select – When a item is selected
  • Change – When the value of the drop down is changed
  • Open – When the drop down list is opened
  • Close – When the drop down list is closed

Here is the code to subscribe to these events:

 
@( 
    Html.Kendo().DropDownList() 
                .Name("kdropdownlist") 
                .DataTextField("Text") 
                .DataValueField("Value") 
                .BindTo(Model) 
                .Events(e => { e.Change("change") .Select("select") .Open("open") .Close("close"); })) 
) 

In the above code we use the Events() method to subscribe to different events. The events like Select, Open, Close, Change receive the names of the JavaScript function and when the event occurs the function will be invoked. Here is the JavaScript functions which log the event as it occurs to a div.


<div class="console"></div>

function open() {
        $(".console").html("<p>event: open</p>");
};

function close() 
{
        $(".console").append("<p>event: close</p>");
};

function change() 
{
        $(".console").append("<p>event: change</p>");
};

function dataBound() 
{
        $(".console").append("<p>event: dataBound</p>");
};

function select(e) 
{
        var dataItem = this.dataItem(e.item.index());
        $(".console").append("event :: select (" + dataItem.Text + " : " + dataItem.Value + ")");
};

DropDownList API:

So far we have seen how to get the drop down list instantiated on the screen, bind data and react to events. What if we need to access the drop down list control on the client side, at run time. All Kendo controls provide a very rich client side API. Using these api’s we can access a control which is already instantiated on the screen using JavaScript. Here is the code to access a drop down list control from JavaScript:

 
$(document).ready(function()
{ 
   var dropdownlist = $("#kdropdownlist").data("kendoDropDownList") 
}); 

On document ready, we use the jquery selector syntax to grab a element with id kdropdownlist and then use the jquery’s data() method to get the kendo drop down object. After this we can perform many of the operation exposed by the object. The methods supported by the drop down list is as follows:

close() closes the drop down list
dataItem() returns raw data record at the specified index
destroy() prepare for safe removal from DOM
enable(bool) enables/disables drop down list
open() opens the drop down list
refresh re-renders items in the list
search(string) selects item which starts with provided parameter
select(jquery|Number|function) selects item and sets the value & text
setDataSource(datasource) sets datasource and rebinds the drop down list
text(string) gets/sets the text of the drop down
toggle(bool) toggles between open & closed states
value(string) gets/sets the value of the drop down

Summary:

In this post we looked at one more commonly used controls – DropDownList. With the ASP.NET wrappers we saw how easy it is to instantiate a control, perform server side or ajax data binding and then how to work with the client side API. Hope you find this useful. Do give it a try i.e. download Kendo Complete and get started with Kendo Wrappers for ASP.NET MVC.

Advertisement

7 thoughts on “Kendo DropDownList Wrapper for ASP.NET MVC

  1. Pingback: Getting Started Series on Kendo UI Wrappers for ASP.NET MVC « Telerik Helper

  2. Pingback: Kendo DropDownList Wrapper for ASP.NET MVC | ermaneesh007

  3. It Was indeed a very good and clear article…….I am stuck on how to implement cascading Kendo dropdownlist which has its data source in database and i want to access that database via ado.net data entity model

  4. Pingback: Top 5 Blog Posts of 2014 | telerik helper

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.