Search code examples
kendo-uikendo-asp.net-mvckendo-comboboxkendo-autocomplete

Add custom data-* attributes to Kendo UI AutoComplete or ComboBox


Currently using the Kendo UI AutoCompleteFor() and ComboBoxFor() helper.

Noticing that they generate/render a bunch of <li>s.

How does one add additional custom data-* attributes to those <li>s?

Here's the current scenario:

  1. The user starts typing stuff in the AutoCompleteFor
  2. An ajax call is triggered to fetch some data related to what the user has typed.
  3. The obtained results are transformed into an IEnumerable<SelectListItem>.
  4. The result is then sent to Json. Json(result, JsonRequestBehavior.AllowGet)

My goal is to add one or more additional data-* attribute to each of these <li> generate lines so that I can fetch these data-* in the onChange() event.

How does one achieve this?

In addition, I'm aware that I could create my own .Template() and possibly achieve my task but I was curious if anyone knows of a different way to do this then having to create my own template.

Sincerely


Solution

  • Ok I've found a solution; I'll share it here in case anyone is interested.

    Instead of transforming my obtained results into an IEnumerable<SelectListItem>, I simply transform this into an IEnumerable<CustomDTO>.

    The CustomDTO class looks like this:

    public class CustomDTO
    {
         public int Value { get; set; }
         public string Text { get; set; }
         public int Age { get; set; }
         //Add whatever more properties you think you’ll need.
    }
    

    In my controller, I then do the following:

    var result = _myService.GetData().ToList();
    return Json(result, JsonRequestBehavior.AllowGet);
    

    Where GetData() returns an IEnumerable<CustomDTO>.

    Inside my View, I have an AutoCompleteFor() control to which I bind a client side .Events(x => x.Select("onSelect") event handler.

    The handler is defined like so:

    function onSelect(e)
    {
        if (e.item == null) return;
        var dataItem = this.dataItem(e.item.index());
        var valueAttribute = dataItem.Value;
        var textAttribute = dataItem.Text;
        var ageAttribute = dataItem.Age;    //This is how I get my additional value
        //...code...
    }
    

    So that's it.