Proper binding of json to Kendo DropDownList

2019-08-11 02:08发布

问题:

I have the following json data (see below) from a webservice query (_urlTowns). I want to bind a Kendo UI dropdownlist control to this datasourceTowns.

{
"displayFieldName": "TNONAM",
"fieldAliases": {
    "TNONAM": "TNONAM"
},
"fields": [{
    "name": "TNONAM",
    "type": "esriFieldTypeString",
    "alias": "TNONAM",
    "length": 16
}],
"features": [{
    "attributes": {
        "TNONAM": "ANSONIA"
    }
}, {
    "attributes": {
        "TNONAM": "BETHANY"
    }
}, {
    "attributes": {
        "TNONAM": "BRANFORD"
    }
}, {
    "attributes": {
        "TNONAM": "WOODBRIDGE"
    }
}]}
// Towns data source
var dataSourceTowns = new kendo.data.DataSource({
transport: {
    read: {
        url: _urlTowns,
        dataType: "json",
        type: 'GET'
    }
},
schema: {
    data: "features"
}});dataSourceTowns.read();

Do I need to set a model attribute? As I'm after populating the DDL with the dataTextValue from "TNONAM". Guess I'm confusing the "features" and "attributes".

回答1:

Maybe your JSON is not the most convenient for a DropDownList but you can bind it to a KendoDropDownList with no change.

Define the DropDownList as:

$("#dropdown").kendoDropDownList({
    dataSource    : dataSourceTowns,
    dataTextField : "attributes.TNONAM"
});

Remember that dataTextField doesn't strictly have to be a field, might be path to the field.

Where your HTML is:

<select id="dropdown"></select>


回答2:

For your dropdown configuration, part of your json need to be:

"features": [{"TNONAM": "ANSONIA"}, 
             {"TNONAM": "BETHANY"},
             {"TNONAM": "BRANFORD"},
             {"TNONAM": "WOODBRIDGE"}]

If json response strictly need to be that, then you may have to parse response data like:

schema: {
        data: function(response) {
            var responsedata = response.features;
            var parsedjson =  []; //use responsedata to make json structure like above
            return parsedjson; 
        }
    }


回答3:

 $("#dropDownList1").kendoDropDownList({
            optionLabel: "Select dropdown",
            dataTextField: "dropdown",
            dataValueField: "dropdown",
            dataSource: {
                type: "json",
                transport: {
                    read: {url: "dropdown.json",
                        type: "GET",
                        dataType: "json",
                        contentType: "application/json; charset=utf-8"
                    }
                }
            },
            schema: {
             data: function(data) {
             alert(JSON.stringify(data));
             return eval(data);
             }
             },   
  • dropdown.json like :[ {"dropdown":"value 1"}, {"dropdown":"value 2"} ]`