Search code examples
asp.net-mvckendo-uitelerikmulti-select

Sort Kendo Multiselects selected Items by DataTextField


We are using kendo multiselect with mvc wrappers. Everything on the setup works fine, but the selected items are sorted by the data value field. I simply want them to be sorted by the data text field, but nothing worked so far.

@(Html.Kendo().MultiSelectFor(m => m.SelectedPersonIds)
      .HtmlAttributes(new { style = "width: 400px" })
      .DataTextField("Name")
      .DataValueField("PersonID")
      .Filter("contains")
      .Height(400)
      .DataSource(ds =>
      {
       ds.Read(read =>
        {
            read.Action("GetPersons", "Person", new { area = "" });
        });
      })
      .ItemTemplateId("detailTemplate")
      .TagTemplateId("valueTemplate")
)

This is the working version. I tried adding

ds.Custom().Sort(s => s.Add("Name").Ascending());

and other approaches, but still no luck. The initial data, coming from the server, is sorted and therefore the list you select from is sorted perfectly (by Name).

How can i achieve that the selected items are also sorted by Name instead of by ID? Thanks in advance.


Solution

  • I don't know is there is ASP.NET solution but i can give you JavaScript to solve it:

    function onMultiselectChange(e) {
            e.sender.tagList.find('> li').sort(function (a, b) {
                return $(a).text() > $(b).text();
            }).appendTo(e.sender.tagList);
        }
    });
    

    You can apply it to your ASP.NET multiselect like this:

    .Events(e =>
        {
            e.Change("onMultiselectChange")
        })