ASP.NET Web API教程 分页查询
首先增加支持分页的API方法
public IEnumerable<UserInfo> GetUserInfos(int pageindex, int size)
{
return bll.Get().Skip((pageindex - 1) * size).Take(size);
}
{
return bll.Get().Skip((pageindex - 1) * size).Take(size);
}
增加一个新页面
引入js
<script src="Scripts/jquery-1.7.1.min.js" type="text/javascript"></script>
<script src="Scripts/knockout-2.1.0.js" type="text/javascript"></script>
<script src="Scripts/knockout-2.1.0.js" type="text/javascript"></script>
编写数据迭代显示模板
<ul data-bind="template: {name: 'userinfoTemplate', foreach: userinfos}">
</ul>
</ul>
UL为数据迭代容器模板
<script id="userinfoTemplate" type="text/html">
<li class="userinfo">
<div class="info">
<strong><span data-bind="text: Name"></span></strong>
<span data-bind="text: Age"></span>
</div>
</li>
</script>
<li class="userinfo">
<div class="info">
<strong><span data-bind="text: Name"></span></strong>
<span data-bind="text: Age"></span>
</div>
</li>
</script>
Script id=’ userinfoTemplate’为数据项模板
编写获取分页操作面板
<fieldset>
<label>第</label><input type="text" id="pageIndex" /><label>页</label><br />
<label>每</label><input type="text" id="pageSize" /><label>条一页</label><br />
<input type="button" value="获取" id="getButton" />
</fieldset>
<label>第</label><input type="text" id="pageIndex" /><label>页</label><br />
<label>每</label><input type="text" id="pageSize" /><label>条一页</label><br />
<input type="button" value="获取" id="getButton" />
</fieldset>
开始编写js根据输入的页码和每页的数量获取
<script type="text/javascript">
viewModel = {
userinfos: ko.observableArray([])
};
ko.applyBindings(viewModel);
$("#getButton").click(function () {
viewModel.userinfos([]);
var pageSize = $('#pageSize').val();
var pageIndex = $('#pageIndex').val();
var url = "/api/userinfo?pageindex=" + pageIndex + '&size=' + pageSize;
$.getJSON(url, function (data) {
// 根据路径得到数据
viewModel.userinfos(data);
});
return false;
});
</script>
viewModel = {
userinfos: ko.observableArray([])
};
ko.applyBindings(viewModel);
$("#getButton").click(function () {
viewModel.userinfos([]);
var pageSize = $('#pageSize').val();
var pageIndex = $('#pageIndex').val();
var url = "/api/userinfo?pageindex=" + pageIndex + '&size=' + pageSize;
$.getJSON(url, function (data) {
// 根据路径得到数据
viewModel.userinfos(data);
});
return false;
});
</script>
最终运行得到结果获取第一页,每一页1条的情况下
获取第一页,每页2条的情况下