使用Knockout我试图用调用WebAPI的Ajax方法返回的数据绑定3个下拉列表。
收到的JSON数据属于" ReconDefMasters"其中calsses的定义如下
public class MasterItem
{
public int MasterItemID { get; set; }
public string MasterItemName { get; set; }
}
public class ReconDefMasters
{
public IList<MasterItem> servFileFormat { get; set; }
public IList<MasterItem> mersRev { get; set; }
public IList<MasterItem> mersFileType { get; set; }
}
如何为此编写ko.mapping?
我能够通过返回IList来实现结果,但是它需要对WebAPI进行3次单独调用,并尝试通过返回3个IList的复合对象来避免这种多次调用。
我引用了以下链接,但没有成功修改3下拉列表的逻辑
http://jsfiddle.net/jearles/CGh9b/
Poblem with getting multidimensional array (object) observable in KnockoutJS
这是我的单个IList&lt;&gt;的代码方法
var apipath = 'http://example.com';
ko.validation.init({
registerExtenders: true,
messagesOnModified: true,
insertMessages: false
});
function Master(data) {
var self = this;
self.FormatId = ko.observable(data.MasterItemID);
self.FormatName = ko.observable(data.MasterItemName);
}
var RuleDefVM = function (url) {
var self = this;
self.ServFileFormat = ko.observableArray();
self.selectedTemplate = ko.observable();
self.RuleDef = function () {
jQuery.support.cors = true;
$.ajax({
type: "GET",
url: url,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response != "") {
$(response).each(function (index, element) {
self.ServFileFormat.push(new Master(element));
});
}
}
});
};
}
var urlRuleDef = apipath + '/api/RuleDef/';
var viewModelRuleDef = new RuleDefVM(urlRuleDef);
viewModelRuleDef.RuleDef();
答案 0 :(得分:0)
function Master(data) {
var self = this;
self.FormatId = ko.observable(data.MasterItemID);
self.FormatName = ko.observable(data.MasterItemName);
}
selfDef.ServFileFormat = ko.observableArray();
selfDef.MERSRev = ko.observableArray();
selfDef.MERSFileType = ko.observableArray();
self.selectedTemplate1 = ko.observable();
self.selectedTemplate2 = ko.observable();
self.selectedTemplate3 = ko.observable();
jQuery.support.cors = true;
$.ajax({
url: url,
type: "GET",
dataType: "json",
contentType: "application/json; charset=utf-8",
cache: false,
success: function (response) {
if (response != "") {
$(response).each(function (index, element) {
$(element.servFileFormat).each(function (index,element) {
selfDef.ServFileFormat.push(new Master(element));
});
$(element.mersRev).each(function (index, element) {
selfDef.MERSRev.push(new Master(element));
});
$(element.mersFileType).each(function (index, element) {
selfDef.MERSFileType.push(new Master(element));
});
});
}
}
});
<select data-bind="options: ServFileFormat, value:selectedTemplate1, optionsText: 'FormatName' "class="dropdown"></select>
<select data-bind="options: MERSRev, value:selectedTemplate2, optionsText: 'FormatName' "class="dropdown"></select>
<select data-bind="options: MERSFileType, value:selectedTemplate3, optionsText: 'FormatName' "class="dropdown"></select>