【发布时间】:2015-11-18 18:08:28
【问题描述】:
我在尝试将我的 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; }
}
}
【问题讨论】:
标签: knockout.js asp.net-web-api