与jQuery验证绑定的单选选项不起作用

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().NameviewModel.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未指定时,错误仍然存​​在:

没有OptionsValue

这是我的对象观察selectedCity:

watch中的viewModel.selectedCity()返回一个对象

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

使用OptionsValue

RP *_*yer 8

问题是当将对象作为值处理时,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/

  • 谢谢,这就是我所拥有的作为一种解决方法,但是对于所有下拉列表来说都是繁琐的.我的knockoutjs脚本正在快速增长,我想知道是否值得努力,因为你失去了mvc Html控件助手,服务器ViewModel数据注释和内置验证支持.当然数据绑定很棒.无论如何,我会将此作为帮助其他搜索者的答案. (3认同)

小智 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验证.