尝试通过webapi从泛型列表转到knockoutjs



我在尝试将webapi数据与knockoutjs绑定时遇到问题。json数据恢复得很好,我相信,但我不知道如何将其放入视图模型中,以便淘汰可以使用它?

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <script src="Scripts/knockout-3.4.0.js"></script>
    <script src="Scripts/jquery-2.1.1.js"></script>
    <meta charset="utf-8" />
</head>
<body>
    <table>
        <thead>
            <tr>
                <th>Code</th>
                <th>Name</th>
            </tr>
        </thead>
        <tbody data-bind="foreach: seats">
            <tr>
                <td data-bind="text: Code"></td>
                <td data-bind="text: Name"></td>
            </tr>
        </tbody>
    </table>

    <script type="text/javascript">
        function AppViewModel() {
            var self = this;
            self.seats = [];
            /*
            [
                { Code: 1, Name: "red" },
                { Code: 2, Name: "blue" }
            ];
            */
            $.get("/api/Test/Get", null, function (data) {
                //callback
                self.seats = data;
            },'json');
        }
        ko.applyBindings(new AppViewModel());
    </script>
</body>
</html>

服务器端

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
namespace WebApplication2.Controllers
{
    public class TestController : ApiController
    {
        [HttpGet]
        public List<UserSettings> Get()
        {
            List<UserSettings> list = new List<UserSettings>();
            UserSettings userSetting  = new UserSettings() { Code = 1, Name = "Name 01" };
            list.Add(userSetting);
            return list;
        }
    }
    public class UserSettings
    {
        public int Code { get; set; }
        public string Name { get; set; }
    }
}

您希望seats是一个可观察性数组。然后,巧妙地,填充它只意味着使它成为get:的成功函数

  $.get("/api/Test/Get", null, self.seats, 'json');

下面的示例使用超时来伪造get,这样您就可以看到填充的发生。

function AppViewModel() {
  var self = this;
  self.seats = ko.observableArray();
  /*
  $.get("/api/Test/Get", null, self.seats, 'json');
  */
  setTimeout(function() {
    self.seats(
      [{
        Code: 1,
        Name: "red"
      }, {
        Code: 2,
        Name: "blue"
      }]);
  }, 800);
}
ko.applyBindings(new AppViewModel());
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
<table>
  <thead>
    <tr>
      <th>Code</th>
      <th>Name</th>
    </tr>
  </thead>
  <tbody data-bind="foreach: seats">
    <tr>
      <td data-bind="text: Code"></td>
      <td data-bind="text: Name"></td>
    </tr>
  </tbody>
</table>

最新更新