Knockout Mapping Plugin无法绑定来自ASp.Net Webapi的Json集合

时间:2012-11-15 12:34:28

标签: knockout.js asp.net-web-api knockout-mapping-plugin

我有以下代码:

/*   Sample data received from an ASP.Net WebApi ajax call  */
var data = { [{"CodSeguro":676541,"NroSeguro":538178},{"CodSeguro":687069,"NroSeguro":577836]},{"CodSeguro":123,"NroSeguro":233]};

/*This function build the view model that will be shared by multiple pages*/
function getViewModel(data)
{
   return ko.mapping.fromJS(data);
}

var viewModel = getViewModel(data);
ko.applyBindings(viewModel);

我的Html看起来像这样:

<table>
<thead>
    <tr>
        <th>CodSeguro</th>
        <th>NroSeguro</th>
        <th>NroEndoso</th>        
    </tr>
</thead>
<tbody data-bind="foreach: ">
  <tr>
    <td>
        <span data-bind="text: CodSeguro"></span>
    </td>
    <td>
        <span data-bind="text: NroSeguro"></span>
    </td>
    <td>
        <span data-bind="text: NroEndoso"></span>
    </td>        
</tr>

简单地说,我不知道在这行之后要放置什么:

我真的需要使用Mapping Plugin,因为有很多ob对象我不想在两个地方编码(js用于淘汰赛,c#用于服务层)

小提琴是这样的:

http://jsfiddle.net/3Q6JE/

感谢!!!

1 个答案:

答案 0 :(得分:1)

您可以将$data放到foreach:

<tbody data-bind="foreach: $data">

但是您的json应该是以下内容:

var data = [{"CodSeguro":676541,"NroSeguro":538178},{"CodSeguro":687069,"NroSeguro":577836},{"CodSeguro":123,"NroSeguro":233}];

这是工作小提琴:http://jsfiddle.net/3Q6JE/2/