Pin*_*hah 9 asp.net asp.net-mvc jquery jquery-validate knockout.js
我正在将一个对象列表绑定到一个select使用的淘汰赛.对象类可以包含任意数量的属性
<select id="TheProperty_City"
name="TheProperty_City"
class="required"
data-bind="options: cityList,
optionsText: 'Name',
value: selectedCity,
optionsCaption: '--select the city--'" />
Run Code Online (Sandbox Code Playgroud)
这非常好用,我可以使用viewModel.selectedCity().Name或viewModel.selectedCity().Value加载子元素.
我的问题是jQuery验证.如果我保留上述语句,jQuery即使在选择后也不会重置错误.
我通过optionsValue在bind中指定它来修复它,但然后selectedCity返回标量值而不是整个对象.任何想法如何保持对象行为或以不同方式进行验证?
<select id="TheProperty_City"
name="TheProperty_City"
class="required"
data-bind="options: cityList,
optionsText: 'Name',
optionsValue: 'Value', //added the optionsValue
value: selectedCity,
optionsCaption: '--select the city--'" />
Run Code Online (Sandbox Code Playgroud)
optionsValue未指定时,错误仍然存在:

这是我的对象观察selectedCity:

这是指定selectedCity何时的对象监视optionsValue:

问题是当将对象作为值处理时,option元素的值设置为"".由于这个原因,jQuery验证失败了.您可以将绑定或包装器绑定写入经过的options绑定,并将它们设置为一个值,但我不认为最好走这条路.
一个不错的选择是存储值并使用dependentObservable来表示当前选定的对象.
这将是:
var viewModel = {
cityList: [{ Name: "Madison", Value: "MSN" }, { Name: "Milwaukee", Value: "MKE" }, { Name: "Green Bay", Value: "GRB" }],
selectedCityValue: ko.observable()
};
viewModel.selectedCity = ko.dependentObservable(function() {
var value = this.selectedCityValue();
return ko.utils.arrayFirst(this.cityList, function(city) {
return city.Value === value;
});
}, viewModel);
Run Code Online (Sandbox Code Playgroud)
有一个绑定像:
<select id="TheProperty_City" name="TheProperty_City" class="required"
data-bind="options: cityList,
optionsText: 'Name',
optionsValue: 'Value',
value: selectedCityValue,
optionsCaption: '--select the city--'" />
Run Code Online (Sandbox Code Playgroud)
示例:http://jsfiddle.net/rniemeyer/EgCM3/
小智 6
相当简洁的解决方案是将optionsAfrerRender参数添加到选项绑定.假设在'selectedCity'对象中有一个字段'cityId',您可以将其分配给选项值.请根据您的示例检查以下解决方案:
<select id="TheProperty_City"
name="TheProperty_City"
class="required"
data-bind="options: cityList,
optionsText: 'Name',
value: selectedCity,
optionsAfterRender: function(option, item)
{ option.value = item.cityId; }
optionsCaption: '--select the city--'" />
Run Code Online (Sandbox Code Playgroud)
使用这种方法,您将获得敲除选项绑定和jquery验证.
| 归档时间: |
|
| 查看次数: |
6340 次 |
| 最近记录: |