问题
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