使用knockoutjs在视图中显示对象

时间:2012-07-17 10:19:35

标签: jquery json asp.net-mvc-3 knockout.js

我需要帮助,我有回复对象的动作(JSON格式,我使用这个approche:“http://code.msdn.microsoft.com/Build-truly-RESTful-API-194a6253”),这里是我从动作返回的对象(DashboardController的索引):

   var model = new DashboardHomeModel()
        {                
            CurrentCompaigns = .....................,
            BuzzLeaderCompaigns = ..................,            
            BuzzCompaignByInterest =  ..................
        };
    return View(model);

首先我要显示我的模型的BuzzLeaderCompaigns(它是Compaign的ICollection),这是我的观点:

               <h3>My Compaign</h3>
       <table>
            <thead>
                  <tr>
                   <th>Compaign Name</th><th>Compaign Description</th><th>End Date</th>
                 </tr>
            </thead>
           <tbody data-bind="foreach: BuzzLeaderCompaigns">
             <tr>
               <td data-bind="text: Name" ></td>            
                <td data-bind="text: Description"></td>
                <td data-bind="text: EndDate"></td>
              </tr>       
          </tbody>
       </table>

 <script type="text/javascript">
      function Compaign(data) {
           this.BuzzCompaignId = ko.observable(data.BuzzCompaignId);
           this.Name = ko.observable(data.Name);
           this.Description = ko.observable(data.Description);
           this.EndDate = ko.observable(data.EndDate);
      }

      function DashboardViewModel() {
           var self = this;
           self.BuzzLeaderCompaigns = ko.observableArray([]);      
           self.CurrentCompaigns = ko.observableArray([]);
           self.BuzzCompaignByInterest = ko.observableArray([]);
        // Load initial state from server, convert it to Task instances, then populate self.tasks
        $.getJSON("/Dashboard/Index", function (Data) {
              var mappedData = $.map(Data, function() { return   } ) ;
      });

      } 
     ko.applyBindings(new DashboardViewModel());

    </script>

如何将我的数据绑定到我的viewmodel(当我使用$ .getJSON获取数据时)然后我的视图

3 个答案:

答案 0 :(得分:1)

假设/ Dashboard / Index返回CurrentCompaigns,请更改:

$.getJSON("/Dashboard/Index", function (Data) {
    var mappedData = $.map(Data, function() { return   } ) ;
});

对此:

$.getJSON("/Dashboard/Index", function (Data) {
    var mappedData = $.map(Data, function(item) { return new Compaign(item) });
    self.CurrentCompaigns(mappedData);
});

然而,您应该考虑Arbiter的建议; / Dashboard / Index听起来像应该返回视图的操作方法,而不是JSON操作方法。您可以为三个observableArrays使用三个单独的JSON方法,或者您可以使用一个返回所有“Compaigns”的方法,然后使用ko.utils.arrayFilter过滤并为三个数组赋值。

答案 1 :(得分:0)

有些事情会让你走上正轨:

  • 如果您的视图(cshtml)被称为“索引”,那么您应该在控制器上创建一个不同的操作来返回您的json。
  • 您应该让新操作返回View(model);而不是返回Json(model, JsonRequestBehavior.AllowGet);,以使操作返回JSON(而不是HTML)。您现有的操作(索引)应返回无模型视图,即return View();
  • 更改getJSON的路径以使用新路径,即:

    $。getJSON(“/ Dashboard / GetCampaign”,function(Data){     填充viewmodel的代码 );

答案 2 :(得分:0)

您可以使用一些服务器端代码将视图模型直接转换为Json字符串:

 <script type="text/javascript">    
        // this example is using Json.Net  
        var model = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model, new Newtonsoft.Json.Converters.IsoDateTimeConverter()));
        // wrapper contains additional methods and logic 
        // knockout mapping plugin is used to convert json objects to observable objects
        var wrapper = new ViewModelWrapper(ko.mapping.fromJS(model));           
        ko.applyBindings(wrapper);
  </script>