我有一个retrieveEntity Web 服务方法,它以json 字符串和数组的形式返回字段。我无法将这些字段绑定到文本框,同时保持视图模型完整。首先,我进行 ajax 调用来初始化我的数据并保存它。然后在我的视图模型中,我检索这些值,并绑定到所需的文本框。这是代码:
<script type="text/javascript" language='javascript'>
jQuery(function () {
myViewModel = new viewmodel();
ko.applyBindings(myViewModel);
});
var invoice = function () {
var initializeURL = "ajaxwebservicecalls.asmx/RetrieveEmptyEntity";
$.ajax({
type: "Post",
url: initializeURL,
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function retrieveemptyesuccess(msg) {
passedmodel = (msg.d.Data);
var data = ko.mapping.fromJS(passedmodel);
var x = $.toJSON(passedmodel)
},
Error: function initializefail(msg) { alert(msg) }
});
}
以下是 X 返回的一小段内容:
{
"Entities": {
"Entity": [{
"Index": "1",
"Name": "BatchNumber",
"Value": ""
}, {
"Index": "2",
"Name": "InvoiceNumber",
"Value": ""
}]
},
"APInvoiceHeader": {
"VoucherNumber": "",
"PayLocationID": "",
"InvoiceDescription": "",
"InvoiceTypeID": "",
"TermsRuleID": "",
"TaxTypeID": "",
"RecurringInvoice": 0,
"APInvoiceItems": [{
"FixedAssetReferences": [{
"FixedAssetReferenceId": 0,
"FixedAssetReferenceIdSpecified": true,
"FormattedGLAccount": ""
}]
}
接下来我根据返回的数据构建我的视图模型:
var passedmodel;
var myViewModel;
var viewmodel = function () {
this.invoice = ko.observable(new invoice());
this.arrayentity = ko.observableArray([new invoice("ff"), new invoice("dd"), new invoice("zz"), new invoice("rr")]);
this.RetrieveEntity = function () {
var retrieveURL = "ajaxwebservicecalls.asmx/RetrieveEntity";
$.ajax({
type: "Post",
url: retrieveURL,
data: {},
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function retrievesuccess(msg) {
passedmodel = msg.d.Data;
myViewModel.invoice(ko.mapping.fromJS(passedmodel, {}, myViewModel)); }
//我希望能够使用上面的,然后在HTML绑定中指定例如:
data-bind="value:myViewModel.invoice().APInvoiceHeader.VoucherNumber"
或者
data-bind="value:myViewModel.arrayentity().Entities.Entity()[0].Name"
但是绑定语法给了我一个错误。相反,我解析了视图模型并且不能将其作为一个整体使用:
myViewModel.invoice(ko.mapping.fromJS(passedmodel.APInvoiceHeader, {}, myViewModel));
或者
myViewModel.arrayentity([(ko.mapping.fromJS(passedmodel.Entities.Entity[0])), (ko.mapping.fromJS(passedmodel.Entities.Entity[1]))]);
然后HTML绑定看起来像
data-bind="value:myViewModel.invoice().VoucherNumber
或者
data-bind="value:myViewModel.arrayentity()[0].Name"
绑定得很好,但这不是我希望视图模型看起来的样子。我需要将视图模型保持为一个并解析或导航的原因是因为我需要下一次更新屏幕上的值,这会更新视图模型,然后将视图模型转换回 JS,并将其传递给另一个保存的 ajax 调用新数据。
有人可以帮忙吗?任何提示将不胜感激。谢谢!