I have a dropdownlist with data-bind;
<asp:DropDownList ID="cmbType" Runat="server" AutoPostBack="False" data-bind="value: moveType">
<asp:ListItem Value="">-- Please Select --</asp:ListItem>
<asp:ListItem Value="0">Car</asp:ListItem>
<asp:ListItem Value="1">Air</asp:ListItem>
</asp:DropDownList>
also I have
var viewModel = {
this.moveType = ko.observable(MoveType);
};
ko.applyBindings(new ViewModel());
where "MoveType" is 0 or 1. This seems to be working fine but only partly. Everything is fine and value from dropdown are selected correctly ONLY if "MoveType" = 1. In case if MoveType = 0, it don't want to select "Car" and instead selected option will be "-- Please Select --" with value "".
The question is simple, why? What am I missing? I can't understand it.
Are You sure that You are not getting any errors in console?
I changed your code into :
var MoveType=1;
var ViewModel = function() {
this.moveType = ko.observable(MoveType);
};
ko.applyBindings(new ViewModel()); // This makes Knockout get to work
and now its seems to work: you can test it Here
"car" has a value of 0
in your drop down list (look at your Value
attributes). That is why 0
causes "car" to be selected. If you want to select "-- Please Select --", you need to set the value to an empty string ""
.
This in turn implies that your javascript moveType
and thus also your C# MoveType
must be a string rather than a number, since "" is not a valid number.
To prevent that I suggest you number your options differently: use Value="1"
for car and Value="2"
for air. Then your "please select" option gets Value="0"
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.