[英]Knockout data-bind issue
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. 其中“ MoveType”为0或1。这似乎工作正常,但只有一部分。 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 "".
一切都很好,并且只有在“ MoveType” = 1的情况下,才可以正确选择下拉菜单中的值。如果MoveType = 0,则它不想选择“ Car”,而是选择选项为“-Please Select-”,值“”。
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). “汽车”在下拉列表中的值为
0
(请查看您的Value
属性)。 That is why 0
causes "car" to be selected. 这就是为什么
0
导致选择“汽车”的原因。 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. 这又意味着您的javascript
moveType
以及C# MoveType
必须是字符串而不是数字,因为“”不是有效数字。
To prevent that I suggest you number your options differently: use Value="1"
for car and Value="2"
for air. 为防止这种情况,我建议您对选项进行不同的编号:对于汽车,请使用
Value="1"
;对于飞机,请使用Value="2"
。 Then your "please select" option gets Value="0"
. 然后,您的“请选择”选项将得到
Value="0"
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.