我的asp.net mvc控制器中有一些硬编码值。 GetPlanList()
返回JsonResult
,它应该由viewmodel.js文件读入并将其分配给ko.observableArray()
,然后将数据绑定到表中。
我遇到的问题是如何从mvc控制器获取结果并将其分配给敲除变量?
MVC控制器:
public JsonResult GetPlanList()
{
List<PlanVm> PlanList = GetPlansListData();
return Json(PlanList, JsonRequestBehavior.AllowGet);
}
public List<PlanVm> GetPlansListData()
{
return new List<PlanVm>()
{
new PlanVm() { PlanName = "706-1", ActiveParticipants = 414, TotalOfAllParticipantShares = 1.22},
new PlanVm() { PlanName = "706-2", ActiveParticipants = 23423, TotalOfAllParticipantShares = 4.00},
new PlanVm() { PlanName = "706-3", ActiveParticipants = 3, TotalOfAllParticipantShares = 564.00},
new PlanVm() { PlanName = "706-4", ActiveParticipants = 123, TotalOfAllParticipantShares = 0.00}
};
}
viewmodel.js文件:
function IssuePlansViewModel() {
var self = this;
self.planName = ko.observable("");
self.numberOfParticipants = ko.observable("");
self.totalShares = ko.observable("");
self.result = ko.observableArray();
return self;
}
return IssuePlansViewModel;
HTML:
<table class="table">
<thead>
<tr>
<td>Plan Name</td>
<td class="hide-mobile txt-right">Number of Participants</td>
<td class="txt-right">Total Shares</td>
</tr>
</thead>
<tbody>
<tr>
<td data-bind="text: planName"></td>
<td class="hide-mobile txt-right" data-bind="text: numberOfParticipants"></td>
<td class="txt-right" data-bind="text: totalShares"></td>
</tr>
</tbody>
</table>
答案 0 :(得分:3)
使用ajax方法从服务器获取json列表并将结果绑定到ajax方法的成功回调中。
但是你应该在你的根ViewModel中有一个计划列表,
var IssuePlansViewModel = function(data) {
var self = this;
self.planName = ko.observable(data.planName);
self.numberOfParticipants = ko.observable(data.numberOfParticipants);
self.totalShares = ko.observable(data.totalShares);
self.result = ko.observableArray(data.result);
return self;
}
function mainViewModel() {
var self = this;
self.plans = ko.observableArray([]);
$.ajax({
type: 'GET',
url: "GetPlanList",
dataType: "json",
contentType: 'application/json; charset=utf-8',
traditional: true, //// traditional option to true
success: function(result) {
ko.utils.arrayForEach(jsonResult, function(data) {
self.plans.push(new IssuePlansViewModel(data));
});
}
});
}
并将mainViewModel绑定到您的html。
哦,在您的HTML中,您可能希望使用foreach循环列出计划,
<tbody data-bind="foreach: plans">
<tr>
<td data-bind="text: planName"></td>
<td class="hide-mobile txt-right" data-bind="text: numberOfParticipants"></td>
<td class="txt-right" data-bind="text: totalShares"></td>
</tr>
</tbody>