我正在使用一个$.getJson来检索json对象到我的视图模型中并应用绑定。它不会显示foreach中的数据绑定。[code] - index.cshtml
@{
ViewData["Title"] = "Home Page";
}
@section Scripts {
<script>
require(['knockout', 'jquery', 'bootstrap', 'components/clients-list.component'], function (ko) {
ko.applyBindings();
});
</script>
}
<!DOCTYPE html>
<head>
<title>Index</title>
</head>
<body>
<div class="text-center">
<h1 class="display-4">Welcome</h1>
<p>Machine Grid</p>
<div>
<table>
<tbody data-bind="foreach: machines">
<tr style="border-bottom: 1px solid #000000;">
<td>
<span data-bind="text: machineid"></span>
</td>
<td>
<span data-bind="text: ports"></span>
</td>
<td>
<span data-bind="value: Weight"></span>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div>
</div>
</body>
<script type="text/javascript">
var AppViewModel = function () {
var self = this;
self.machines = ko.mapping.fromJS([]);
$.getJSON('/Home/Index/', function (data) {
self.machines = ko.mapping.fromJS(data);
});
};
$(document).ready(function () {
var viewModel = new AppViewModel();
ko.applyBindings(viewModel);
});
</script>
//Models.MachineModel
public class MachineModel
{
public int MachineId { get; set; }
public string HardDrive { get; set; }
public string Ports { get; set; }
public string GraphicsCard { get; set; }
public string Weight { get; set; }
public string Power { get; set; }
public string Processor { get; set; }
public string Ram { get; set; }
}
//Controller
public async Task<IActionResult> Index()
{
IEnumerable<MachineModel> machineList;
using (var httpClient = new HttpClient())
{
using (var response = await httpClient.GetAsync("https://localhost:44336/api/Machine"))
{
string apiResponse = await response.Content.ReadAsStringAsync();
machineList = JsonConvert.DeserializeObject<IEnumerable<MachineModel>>(apiResponse);
}
}
return View(machineList);
}
有一个填充的对象,我在调试时检查过。我也试过使用Json(machineList),但那会出现一个下载Json的对话框,然后终止。
2条答案
按热度按时间dhxwm5r41#
我能看到一些东西,
data-bind="value: someProperty"
。通常这是<input />
元素。<pre data-bind="text: ko.toJSON($root)"></pre>
添加到html中,以帮助获得视图模型中数据状态的视图第一个
z31licg02#
公共异步任务索引(){