Job*_*mno 0 jquery asp.net-mvc-3 knockout.js
我有web应用程序,我正在尝试使用knockout.js填充我的html表,但我的表仍然是空的.我的数据是通过ajax调用的.jQuery和Knockout.js都引用了我的页面.这是代码;
HTML
<table id="payment_schedule">
<thead>
<tr class="tableHeader">
<th width="50px">
Index
</th>
<th width="50px">
Due Date
</th>
</tr>
</thead>
<tbody>
<tr data-bind="foreach: paymentSchedules">
<td data-bind="text: Index"></td>
<td data-bind="text: Month"></td>
</tr>
</tbody>
</table>
Run Code Online (Sandbox Code Playgroud)
JavaScript函数
function GetComputation() {
$.ajax({
url: '/UnitSearch/CalculateMortgage',
cache: false,
dataType: 'json',
success: function (data) {
viewModel.paymentSchedules(data.PaymentSchedules);
}
});
}
var data = [];
var viewModel = {
paymentSchedules: ko.observableArray(data)
};
ko.applyBindings(viewModel);
Run Code Online (Sandbox Code Playgroud)
从ajax返回的数据

你的代码应该工作正常.你还没有显示你在调用GetComputation函数的位置,但这里有一个完整的例子.
控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
}
public class UnitSearchController : Controller
{
public ActionResult CalculateMortgage()
{
var data = new
{
PaymentSchedules = new[]
{
new { Index = "Reservation Fee", Month = "23-Jan-13" },
new { Index = "Reservation Fee", Month = "25-Jan-13" },
}
};
return Json(data, JsonRequestBehavior.AllowGet);
}
}
Run Code Online (Sandbox Code Playgroud)
索引视图(~/Views/Home/Index.cshtml):
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<table id="payment_schedule">
<thead>
<tr class="tableHeader">
<th>Index</th>
<th>Due Date</th>
</tr>
</thead>
<tbody data-bind="foreach: paymentSchedules">
<tr>
<td data-bind="text: Index"></td>
<td data-bind="text: Month"></td>
</tr>
</tbody>
</table>
<script type="text/javascript" src="@Url.Content("~/scripts/jquery-1.7.1.js")"></script>
<script type="text/javascript" src="@Url.Content("~/scripts/knockout-2.1.0.js")"></script>
<script type="text/javascript">
var data = [];
var viewModel = {
paymentSchedules: ko.observableArray(data)
};
ko.applyBindings(viewModel);
function GetComputation() {
$.ajax({
url: '/UnitSearch/CalculateMortgage',
cache: false,
success: function (data) {
viewModel.paymentSchedules(data.PaymentSchedules);
}
});
}
// I am calling the GetComputation function immediately in this example
// to populate the table with data but you could call it whenever you want
GetComputation();
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
在这个例子中,我GetComputation立即调用,但您可以调整代码并随时调用它.还要注意我已经应用data-bind="foreach: paymentSchedules"了<tbody>而不是<tr>元素.
| 归档时间: |
|
| 查看次数: |
1891 次 |
| 最近记录: |