data使用web api asp.net mvc中的knockout绑定嵌套的json数据

时间:2015-02-06 12:40:11

标签: json asp.net-mvc-4 knockout.js asp.net-web-api

我试图从web api调用绑定一些嵌套的json数据。我是否需要为嵌套数据创建另一个observable,或者是否需要敲除。我有一个从api返回的作业对象,该作业有一个作业列表。我想绑定jobId和joblistID。我只是想找一个简单的方法来做这个json代码

[
    {
        "$id":"1",
        "JobID":1,
        "JobsListID":1,
        "BookingID":1,
        "TimeAllowed":20,
        "TimeTaken":22,
        "Comments":"Some comments",
        "Status":"complete",
        "Notes":null,
        "TimeStarted":"2014-11-04T09:00:00",
        "Difficulty":1,
        "CompleteDate":"2014-11-04T09:22:00",
        "booking":null,
        "jobs_mechanics":[],
        "jobslist": {
            "$id":"2",
            "JobsListID":1,
            "JobCategoryID":1,
            "Description":"Change Tyres",
            "Name":"Tyres",
            "jobs": [
                {"$ref":"1"}
            ],
            "jobscategory":null,
            "model_jobslist":[]
        },
        "timessheets":[]
    }
]

HTML

                      <table class="table table-bordered table-hover">
          <tr>
      <th>Job ID</th>
           <th>JobList ID</th>

     </tr>
        <tbody data-bind="foreach: Jobs">
    <tr>
        <td data-bind="text: JobID"></td>
    </tr>

                              工作清单ID或名称或任何来自                                  工作清单到这里只是为了                                     了解如何显示嵌套数据

                  </td>
               </tr>
             </table>



  script code 
           <script>
var ViewModel = function () {
    var self = this;
    self.Jobs = ko.observableArray();
    self.error = ko.observable();


    var JobsApi = 'http://localhost:54155/api/mechanicphone';

    function ajaxHelper(uri, method, data) {
        self.error(''); // Clear error message
        return $.ajax({
            type: method,
            url: uri,
            dataType: 'json',
            contentType: 'application/json',
            data: data ? JSON.stringify(data) : null
        }).fail(function (jqXHR, textStatus, errorThrown) {
            self.error(errorThrown);
        });
    }
    function getAllJobs() {
        ajaxHelper(JobsApi, 'GET').done(function (data) {
            self.Jobs(data);
        });
    }

    getAllJobs();


};


ko.applyBindings(new ViewModel());

1 个答案:

答案 0 :(得分:0)

您只需使用foreach,然后将joblistId用作jobslist.JobsListID,如下所示:

<table>
    <thead>
        <tr>
            <th>Job ID</th>
            <th>JobList ID</th>
        </tr>
    </thead>
    <tbody data-bind="foreach: Jobs">
        <tr>
            <td data-bind="text: JobID"></td>
            <td data-bind="text: jobslist.JobsListID"></td>
        </tr>
    </tbody>
</table>

JsFiddle