我只需创建一个选择列表绑定,如下所示
<select id="listingstatus" data-bind="options: ListingTypeArrary, optionsText: 'Text', optionsValue: 'Value', selectedOptions: ListingType" ></select>
我的模特
var listArray = JSON.parse([{
"Selected": false,
"Text": "Commercial",
"Value": "4"
}, {
"Selected": false,
"Text": "Residential",
"Value": "5"
}]);
self.ListingTypeArrary = ko.observableArray();
$.each(listArray, function (index, value) {
var obj = {};
obj["Text"] = value.Text;
obj["Value"] = value.Value;
self.ListingTypeArrary.push(obj);
});
self.ListingType = ko.observable('@Model.ListingTypeId'); // @Model.ListingTypeId will be equals to 5
做完这个淘汰后,完美呈现我的下拉列表/选择列表。但我要求我不必显示下拉列表我只需要将所选项目显示为文本。任何人都可以帮助我吗?
提前致谢。
答案 0 :(得分:1)
如果我理解正确,一旦用户做出选择,您希望<select>
消失,并在其位置显示文字标签。
您必须根据所选的Value
计算该标签,然后有条件地显示<select>
或文字标签。
<!-- ko ifnot: SelectedListingText -->
<select id="listingstatus" data-bind="
options: ListingTypeArray,
optionsText: 'Text',
optionsValue: 'Value',
value: ListingType"></select>
<!-- /ko -->
<!-- ko if: SelectedListingText -->
<span data-bind="text: SelectedListingText"></span>
<!-- /ko -->
var listArray = [
{
"Selected": false,
"Text": "Commercial",
"Value": "4"
},
{
"Selected": false,
"Text": "Residential",
"Value": "5"
}
];
// Synthesize the listing type array for the select
ListingTypeArray = ko.observableArray([{ Text: 'Choose one', Value: null }]);
$.each(listArray, function (index, value) {
var obj = {};
obj["Text"] = value.Text;
obj["Value"] = value.Value;
ListingTypeArray.push(obj);
});
// The chosen listing type
ListingType = ko.observable();
// Compute the label text based on the selected Value
SelectedListingText = ko.computed(function () {
type = ListingType();
if(!type) return;
// Find the text associated with this type
var foundListingTypeName;
$.each(listArray, function (index, listingType) {
if(listingType.Value == type) {
foundListingTypeName = listingType.Text;
return false;
}
});
return foundListingTypeName;
});