2015-08-28 45 views
1

我的asp.net mvc控制器中有一些硬編碼值。 GetPlanList()返回JsonResult,它應該由viewmodel.js文件讀入並將其分配給ko.observableArray(),然後將數據綁定到該表。將Asp.Net MVC json結果綁定到knockout.js observable Array

我遇到的問題是如何從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> 

回答

1

使用一個Ajax方法從服務器獲取的JSON列表並綁定結果成功回調ajax方法。

但是你應該有你的根視圖模型計劃的列表,

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> 
+0

不得不做出一些細微的變化,但得到它的工作。謝謝。 –

+0

很高興它的工作。 – Azadrum