[英]How to bind a default selected row from table in knockout js
在我的應用程序中,Iam通過調用Web Api服務來綁定表。
我已經編寫了代碼來在選擇特定行時顯示所選行,並且它工作正常。
現在,我想在web api方法返回成功消息后默認顯示所選行。
我應該如何在成功方法中調用'SelectConfig'。 當我嘗試它什么都不返回。 請幫我擺脫這些問題。
我的HTML:
<tbody data-bind="foreach: datas">
<tr>
<td style="vertical-align: middle;">
<asp:CheckBox ID="chkChild" runat="server" />
</td>
<td style="vertical-align: middle;">
<a id="aTag" data-bind="text: (Name().length > 20 ? Name().substring(0, 20) + '....' : Name()), value: ID, click: $parent.SelectConfig"></a>
</td>
<td style="vertical-align: middle;" data-bind="text: Type == '' || Type == null || Type == undefined ? '--' : Type"></td>
</tr>
</tbody>
<div data-bind="with: Selected, visible: isVisibleDetails">
<div class="col-md-8 value" data-bind="text: (Name() == '' || Name() == null || Name() == undefined) ? '--' : Name">
<select id="ddlType_E" data-bind="options: $root.ddlTypes, optionsText: 'Type', optionsValue: 'ID', optionsCaption: 'Select..', value: selectedTypeId" class="form-control"></select>
</div>
我的視圖模型:
<script type="text/javascript">
function oppConfig(ID, Name,TypeID) {
this.ID = ko.observable(ID);
this.Name = ko.observable(Name);
this.selectedTypeId = ko.observable(TypeID);
}
function ViewModel() {
var self = this;
this.datas= ko.observableArray([]);
getdatas();
this.ddlTypes = ko.observableArray([]);
getOppType();
}
this.Selected = ko.observable(this.datas()[0]);
//selectItem
this.SelectConfig = function (oppConfig) {
alert(ko.toJSON(oppConfig));
self.Selected(oppConfig);
}
function datas() {
$.ajax({
type: "GET",
url: '---',
dataType: "json",
cache: false,
crossDomain: true,
processData: true,
success: function (data) {
self.datas.destroyAll();
if (data.length > 0) {
$.each(data, function (index) {
self.datas.push(new oppConfig(data[index].ID, data[index].Name, data[index].Type));
});
//Here, I want the to call the select config
}
else {
}
},
error: function (data) {
}
});
}
ko.applyBindings(new ViewModel());
</script>
您需要將數據綁定包含在HTML標記中的<tr>
元素中。 現在,您具有所選內容的顯示div,但不具有所選值本身。
<tbody data-bind="foreach: model.datas">
<tr data-bind="click: $root.selectThing, css: { selected: isSelected} ">
然后在視圖模型中,添加一個函數以返回所選的東西:還為對象本身添加一個observable。
function ViewModel() {
var self = this;
this.datas= ko.observableArray([0]);
getdatas();
this.ddlTypes = ko.observableArray([]);
getOppType();
self.CurrentDisplayThing = ko.observable();
self.selectThing = function(item){
self.model.CurrentSelected = ko.observable();
}
}
最后,在表示配置類的對象中,添加一個isSelected變量,這是一個knockout函數。
function oppConfig(ID, Name,TypeID) {
this.ID = ko.observable(ID);
this.Name = ko.observable(Name);
this.selectedTypeId = ko.observable(TypeID);
self.isSelected = ko.computed(function(){
return selected() === self;
}
}
一些CSS顯示您的選擇:
.selected { background-color: yellow; }
thead tr {
border:1px solid black;
background:lightgray;
}
tbody tr {
border:1px solid black;
cursor: pointer;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.