Knockout-Kendo dropdownlist Ajax observableArray get selected item name

北慕城南 提交于 2019-12-10 10:26:57

问题


My application is MVC 5, I use the following Knockout-kendo dropdown list:

 <input data-bind="kendoDropDownList: { dataTextField: 'name', dataValueField: 'id', data: foodgroups, value: foodgroup }" />

   var ViewModel = function () {
        var self = this;
         this.foodgroups = ko.observableArray([
         { id: "1", name: "apple" },
         { id: "2", name: "orange" },
         { id: "3", name: "banana" }
         ]);
        var foodgroup =
        {
            name: self.name,
            id: self.id
        };

        this.foodgroup = ko.observable();
        ko.bindingHandlers.kendoDropDownList.options.optionLabel = " - Select -";
        this.foodgroup.subscribe(function (newValue) {
            newValue = ko.utils.arrayFirst(self.foodgroups(), function (choice) {
                return choice.id === newValue;
            });

            $("#object").html(JSON.stringify(newValue));
           alert(newValue.name);
        });
    };
    ko.applyBindings(new ViewModel());

It works great, thanks to this answer Knockout Kendo dropdownlist get text of selected item

However when I changed the observableArray to Ajax:

       this.foodgroups = ko.observableArray([]),
                $.ajax({
                    type: "GET",
                    url: '/Meals/GetFoodGroups',

                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        self.foodgroups(data);
                    },
                    error: function (err) {
                        alert(err.status + " : " + err.statusText);
                    }
                });

Controller - get the table from ms sql server:

 public JsonResult GetFoodGroups()
            {
                var data = db.FoodGroups.Select(c => new
                {
                    id = c.FoodGroupID,
                    name = c.FoodGroupName
                }).ToList();

                return Json(data, JsonRequestBehavior.AllowGet);
            }

I get this error when I alert the item name

 Unable to get property 'name' of undefined or null reference

What is the difference between hardcoding the array items from using Ajax.


回答1:


The 'id' field has string datatype in hard coded array.

The 'id' field has number datatype in ajax array.

.

So, the 'id' field has different datatypes in both arrays. However in-condition you have used === operator so it checks value as well as datatype.

For ajax array value is same but its datatype is different so its not returning result.

Let me know if any concern.



来源:https://stackoverflow.com/questions/35400673/knockout-kendo-dropdownlist-ajax-observablearray-get-selected-item-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!