This is a migrated thread and some comments may be shown as answers.

Cascading Dropdownlist

5 Answers 290 Views
DropDownList
This is a migrated thread and some comments may be shown as answers.
Otsile
Top achievements
Rank 1
Otsile asked on 14 Aug 2014, 12:38 PM
Please help, I am trying to implement a cascading dropdownlist on my app, but it does not work. Please help me what is it that I am not doing right here:

My controller

namespace TelerikMvcDropdownMunicipality.Controllers
{
    using System.Linq;
    using System.Web.Mvc;
    using TelerikMvcDropdownMunicipality.Models;
    using System.Data;
    using System.Data.Entity;
 
 
 
    public partial class MunicipalController : Controller
    {
               
        public ActionResult Index()
        {
            return View();
        }
 
        public JsonResult GetCascadeDistricts()
        {
            var municipality = new MunicipalityEntities();
 
            return Json(municipality.Districts.Select(d => new { DistrictId = d.DistrictId, DistrictName = d.DistrictName }), JsonRequestBehavior.AllowGet);
 
        }
 
        public JsonResult GetCascadeLocals(int? districts)
        {
            var municipality = new MunicipalityEntities();
            var locals = municipality.Locals.AsQueryable();
 
            if (districts != null)
            {
                locals = locals.Where(l => l.DistrictId == districts);
            }
 
            return Json(locals.Select(l => new { LocalId = l.LocalId, LocalMunName = l.LocalName }), JsonRequestBehavior.AllowGet);
        }
 
        public JsonResult GetCascadeTowns(int? locals)
        {
            var municipality = new MunicipalityEntities();
            var towns = municipality.Towns.AsQueryable();
 
            if (locals != null)
            {
                towns = towns.Where(t => t.LocalId == locals);
            }
 
            return Json(towns.Select(t => new { TownId = t.TownId, TownName = t.TownName }), JsonRequestBehavior.AllowGet);
        }
    }
}


and my view is:

@{
    ViewBag.Title = "Index";
}
 
<div class="demo-section" style="width: 250px;">
 
    <h2>Municipalities</h2>
    <p>
        <label for="districts"> Districts</label>
        @(Html.Kendo().DropDownList()
              .Name("districts")
              .HtmlAttributes(new { style = "width:200px" })
              .OptionLabel("Select district...")
              .DataTextField("DistrictName")
              .DataValueField("DistrictId")
              .DataSource(source =>
               {
                  source.Read(read =>
                  {
                     read.Action("GetCascadeDistricts", "ComboBox");
                  });
             })
          )
                               
        
    </p>
    <p>
        <label for="locals">Locals</label>
        @(Html.Kendo().DropDownList()
        .Name("locals")
        .HtmlAttributes(new { style = "width:200px" })
        .OptionLabel("Select local...")
        .DataTextField("LocalName")
        .DataValueField("LocalId")
        .DataSource(source =>
                        {
                            source.Read(read =>
                                {
                                    read.Action("GetCascadeLocals", "ComboBox")
                                        .Data("filterLocals");
                                        })
                                .ServerFiltering(true);
                        })
                        .Enable(false)
                        .AutoBind(false)
                        .CascadeFrom("districts")
        )
        <script>
            function filterLocals() {
                return {
                    districts: $("#districts").val()
                };
            }
        </script>
    </p>
    <p>
        <label for="towns">Towns</label>
        @(Html.Kendo().DropDownList()
              .Name("towns")
              .HtmlAttributes(new { style = "width:200px" })
              .OptionLabel("Select towns")
              .DataTextField("TownName")
                .DataValueField("TownId")
                                .DataSource(source =>
                                {
                                    source.Read(read =>
                                        {
                                            read.Action("GetCascadeTowns", "ComboBox")
                                                .Data("filterTowns");
                                        })
                                        .ServerFiltering(true);
                                })
                                .Enable(false)
                                .AutoBind(false)
                                .CascadeFrom("towns")
        )
        <script>
            function filterTowns() {
                return {
                    towns: $("#filterTowns").val()
                };
            }
        </script>
    </p>
</div>
 
<script>
    $(document).ready(function () {
        var districts = $("#districts").data("kendoDropDownList"),
            locals = $("#localMun").data("kendoDownList"),
            towns = $("#towns").data("kendoDropDownList");
 
        $("#get").click(function () {
            var districtInfo = "\nDistricts: { id: " + districts.value() + ", name: " + districts.text() + " }",
                localInfo = "\nLocal: { id: " + locals.value() + ", name: " + locals.text() + " }",
                townInfo = "\nTown: { id: " + towns.value() + ", name: " + towns.text() + " }";
 
            alert("Town details:\n" + districtInfo + localInfo + townInfo);
        });
    });
</script>

5 Answers, 1 is accepted

Sort by
0
Georgi Krustev
Telerik team
answered on 18 Aug 2014, 08:35 AM
Hello Otsile,

At first glance, the cascading functionality is implemented correctly. The first two widgets are defined properly. The third one, however, cascades from "towns", which I believe should be "locals". Also values send to the server are retrieved from "filterTowns". Is there a such element on the page?
If the problem still persists I will ask you to send us a runnable test project, which reproduces the problem. Thus we will be able to investigate the problematic page locally and advice you further.

Regards,
Georgi Krustev
Telerik
 
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
 
0
Otsile
Top achievements
Rank 1
answered on 18 Aug 2014, 12:58 PM
I have  tried to attached test project but it seems as if the file cannot be attached, I have saved them on my dropbox here is the link to download it from ~~> https://www.dropbox.com/s/hfp9i2uceq1g64o/CascadingMvcDropdownMunicipality.zip
0
Georgi Krustev
Telerik team
answered on 19 Aug 2014, 09:10 AM
Hello Otsile,

Thank you for the attached test project (as a side note the max size of the allowed file is 20MB). I was able to run it and observe that the first widget is not bound (stays empty). After further investigation, I noticed that the widgets point to ComboBox controller​, rather than to Municipal. Changing the configuration to this one should resolve the problem:
...
source.Read(read =>
{
  read.Action("GetCascadeDistricts", "Municipal");
});
Please note that I was not able to display the items, because the project was pointing to a data base that is not available in the archive.

Regards,
Georgi Krustev
Telerik
 
Join us on our journey to create the world's most complete HTML 5 UI Framework - download Kendo UI now!
 
0
Manish
Top achievements
Rank 1
answered on 06 May 2017, 02:55 PM

Hi,
I am using cascade dropdownlist using OData anf filter options also using parameter map and I am having 3 dropdown.
All binding I did from html page and is working fine from binding side. Now cascade works only in first two dropdown but not with 3rd dropdown.
My unique case is that I am having only one datasource and using same datasource I am applying different filters for 3 dropdowns like first to second and second to third and using some column as from field.

I am not able to get why is working only for first two dropdown and seen that 3rd one is always enabled but when I change value in 2nd , the value is 3rd is populating.
Also while loading the page even if 3rd dropdown is using from field of 2nd then why query is being fired to get the filters and data.

Please help as I discussed in my team but no luck till date, even not able to find in telerik about using one datasource for casacading. FYI --> I tried cascade method from code also but same issue.

Code glimpse:

private initializeArea() {        const requestUrl = this.modelServiceUrl +            '/ObjectInstances()?$filter=TypeName eq \'Production Area\' and FullyQualifiedNames/any(z:startswith(z/Uri,\'' +            this.baseFqn +            '\'))',            options = {                url: requestUrl,                model: {                    fields: {                        ShortDisplayName: { type: 'string' },                        Id: { type: 'int' }                    }                },                sorting: { field: 'ShortDisplayName', dir: 'asc' }            };        this.set('areas', new kendo.data.DataSource(EmsConsole.Console.createODataDataSourceOptions(options)));    }    private initializeEquipmentType() {        const requestUrl = this.modelServiceUrl + '/ObjectInstances()',            options = {                url: requestUrl,                //parameterMap(data) {                //    const result = kendo.data.transports['odata-v4'].parameterMap(data);                //    if (result.$filter) {                //        result                //            .$filter =                //            '(substringof(\':FACILITY_ELEMENT:\',ObjectType/Uri) or ObjectType/Name eq \'FACILITY_ELEMENT\') and (TypeName ne null) and ' + result.$filter;                //        result.$filter = result.$filter                //            .replace(/Id/g, 'AncestorRelation/any(z:z/AncestorObjectInstanceId') +                //            ')';                //    }                //    return result;                //},                model: {                    fields: {                        ShortDisplayName: { type: 'string' },                        Id: { type: 'int' },                        TypeName: { type: 'string' }                    }                },                sorting: { field: 'TypeName', dir: 'asc' },                parse(data) {                    data = EmsCommon.Common.insertDistinctValues(data, 'TypeName');                    return data;                }            };        this.set('equipmentTypes',            new kendo.data.DataSource(EmsConsole.Console.createODataDataSourceOptions(options)));    }    private initializeEquipmentName() {        const that = this,            requestUrl = this.modelServiceUrl + '/ObjectInstances()',            options = {                url: requestUrl,                parameterMap(data) {                    const result = kendo.data.transports['odata-v4'].parameterMap(data);                    //if (data.filter.filters[0].value === ' ')                    //    $.Callbacks().disable();                    if (result.$filter) {                        result                            .$filter =                            '(substringof(\':FACILITY_ELEMENT:\',ObjectType/Uri) or ObjectType/Name eq \'FACILITY_ELEMENT\') ' +                            'and (ShortDisplayName ne null) and AncestorRelation/any(z:z/AncestorObjectInstanceId eq ' +                            that.selectedArea + ' and ' + result.$filter + ')';                    }                    return result;                },                model: {                    fields: {                        ShortDisplayName: { type: 'string' },                        Id: { type: 'int' },                        TypeName: { type: 'string' }                    }                },                sorting: { field: 'ShortDisplayName', dir: 'asc' },                parse(data) {                    data = EmsCommon.Common.insertDistinctValues(data, 'ShortDisplayName');                    return data;                }            };        this.set('equipmentNames',            new kendo.data.DataSource(EmsConsole.Console.createODataDataSourceOptions(options)));        //that.set('isNameDisabled', true);    }

0
Ianko
Telerik team
answered on 09 May 2017, 10:06 AM

Hello Manish,

The case you have is different from the one discussed in this forum thread. This is why it would be better to be examined in a fresh forum thread. Please open a new forum thread or support ticket and elaborate more on the case. If possible, provide a simple, locally runnable project that demonstrates the difficulties you have so that we can examine the case properly. 

Regards,
Ianko
Telerik by Progress
Try our brand new, jQuery-free Angular 2 components built from ground-up which deliver the business app essential building blocks - a grid component, data visualization (charts) and form elements.
Tags
DropDownList
Asked by
Otsile
Top achievements
Rank 1
Answers by
Georgi Krustev
Telerik team
Otsile
Top achievements
Rank 1
Manish
Top achievements
Rank 1
Ianko
Telerik team
Share this question
or