Knockout js , mvc drop down default value is not selecting

 ̄綄美尐妖づ 提交于 2019-12-14 02:59:39

问题


it seems so simple but I am unable to do it.

I have bounded a Dropdown list with Json data from c#.

View page

<div class="col-md-6">
    <select data-bind="options: VehicleTypes, optionsText: 'Name', optionsValue:'ID', optionsCaption: 'All', value: VehicleTypeId" class="form-control"></select>
</div>

Json call

Knockout Model

var baseModel = {
    VehicleTypeId: null,
    VehicleTypes: [],
}

 var viewModel =  ko.mapping.fromJS(baseModel);

 $.get(urlPath + "/GetVehicleTypes", function (data) {     
      viewModel.VehicleTypes(data);
 });

It does fill up the drop down and when I select a value in drop down value gets updated for VehicleTypeId.

My problem is I want to set a default value for my drop down list, I have googled it but nothing is workign for me

Data I am getting back in Json is as follow.

[{
    "ID": 32,
    "Name": "Vehicle 1"
}, {
    "ID": 30,
    "Name": "Vehicle 2"
}, {
    "ID": 31,
    "Name": "Vehicle 3"
}]

回答1:


Your VehicleTypes need to be in an observableArray and make sure you apply your bindings:

var baseModel = {
                // data
                VehicleTypeId: ko.observable(null),
                VehicleTypes: ko.observableArray([{
                    "ID": 32,
                    "Name": "Vehicle 1"
                }, {
                    "ID": 30,
                    "Name": "Vehicle 2"
                }, {
                    "ID": 31,
                    "Name": "Vehicle 3"
                }]),
            }

            ko.applyBindings(baseModel);



回答2:


You will have to assign a value to the VehicleTypeId so that the Default value is set.

Here is a working example.

function VehicleTypesViewModel(){
    var self = this;
  self.VehicleTypeId = null;
  self.VehicleTypes = [];   
}    
var viewModel =  new VehicleTypesViewModel();

$.get(urlPath + "/GetVehicleTypes", function (data) {     
  viewModel.VehicleTypeId = 32;
  viewModel.VehicleTypes = data;
  ko.applyBindings(viewModel);
});


来源:https://stackoverflow.com/questions/24146318/knockout-js-mvc-drop-down-default-value-is-not-selecting

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