【发布时间】:2018-01-10 02:08:06
【问题描述】:
尝试使用 Knockout 填充表格。
控制器:
public JsonResult GetAllStudents()
{
using (HttpClient client = new HttpClient())
{
client.BaseAddress = new Uri(_apiInfo.Urlapi);
MediaTypeWithQualityHeaderValue contentType =
new MediaTypeWithQualityHeaderValue("application/json");
client.DefaultRequestHeaders.Accept.Add(contentType);
HttpResponseMessage response = client.GetAsync("/api/students").Result;
string stringData = response.Content.ReadAsStringAsync().Result;
if (response.IsSuccessStatusCode)
{
return Json(stringData);
}
return null;
}
}
查看:
<table>
<thead>
<tr><th>Last name</th></tr>
</thead>
<tbody data-bind="foreach: people">
<tr>
<td data-bind="text: $data.lastName"></td>
</tr>
</tbody>
</table>
脚本:
function AppViewModel() {
var self = this;
self.people = ko.observableArray([]),
$.ajax({
type: "GET",
url: '@Url.Action("GetAllStudents", "Konckout")',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
self.people(data);
},
error: function (err) {
alert(err.status + " : " + err.statusText);
}
});
}
ko.applyBindings(new AppViewModel());
我使用 alert(data) 测试了返回,得到以下结果:
[{"id":1,"lastName":"Alexander"},{"id":1,"lastName":"Mike"}]
但是表格中没有数据显示!
【问题讨论】:
-
出于好奇,为什么你有一个控制器可以调用 WebAPI 而不是直接从 javascript 调用 WebAPI?
-
我正在从另一个 WebAPI 服务获取数据。
-
您的 URL 值中有一个拼写错误,
Konckout而不是Knockout。此外,您不能在无法编译的 .js 文件中使用@Url....。您需要使用适当的路径,/Knockout/GetAllStudents -
约翰,谢谢。 @Url 有效,我正在获取数据值。
标签: c# knockout.js asp.net-core