我有一个retrieveEntity Web服务方法,它返回字段作为json字符串和数组。我无法将这些字段绑定到文本框,同时保持视图模型不变。首先,我进行ajax调用以初始化我的数据并保存。然后在我的viewmodel中,我重新检查值,并绑定到所需的文本框。这是代码:
<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": ""
}]
}
接下来,我根据返回的数据构建我的viewmodel:
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"
然而,绑定语法给了我一个错误。而我已经解析了viewmodel并且不能将它作为一个整体使用:
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"
哪个绑定很好,但这不是我希望viewmodel看起来像。 我需要将viewmodel保持为一个并解析或导航的原因是因为我需要在屏幕上更新下一个值,更新viewmodel,然后将viewmodel转换回JS,并将其传递给另一个保存的ajax调用新数据。
有人可以帮忙吗?任何提示都会非常感激。谢谢!