AJAX分页和搜索,一般是两个文件,主文件aspx一般是显示搜索表单,而ascx分部视图中显示列表,一般代码如下:
<%=Html.TextBox("UserName") %>
<input type="button" id="search" value="搜索" />
<div id="List">
<%Html.RenderPartial("UCList", Model); %>
</div>
需要对按钮进行触发,JS代码如:
<script type="text/javascript">
$(function () {
$("#search").click(function () {
var userName = $("#UserName").val();
$.ajax({
type: "post",
url: "/TestPager/Index",
data: "userName=" + userName,
success: function (html) {
$('#List').html(html);
}
});
});
});
</script>
ASCX文件可能是这样的:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Entity.PagedList<MvcApplication1.Models.UserBases> >" %>
<table>
<thead>
<tr>
<td>
姓名
</td>
<td>
更新时间
</td>
</tr>
</thead>
<tbody>
<%if (Model != null)
{
foreach (var i in Model)
{ %>
<tr>
<td>
<%=i.Name%>
</td>
<td>
<%=i.UpdateDate %>
</td>
</tr>
<%}
} %>
</tbody>
<tfoot>
<tr>
<td colspan="2">
<%=Html.AjaxPager(Model, "List", "Index", "TestPager")%>
</td>
</tr>
</tfoot>
</table>
所对应的controller可能是这样的:
#region AJAX分页和查询
/// <summary>
/// AJAX分页与查询测试
/// </summary>
/// <param name="userName"></param>
/// <param name="page"></param>
/// <returns></returns>
public ActionResult Index(string userName, int? page)
{
pp = new Entity.PagingParam(page ?? 1, 3);
if (!string.IsNullOrEmpty(userName))
vp.AddItem("userName", userName);
Entity.PagedList<Models.UserBases> model = GetModel(vp, pp);
model.AddParameters = new System.Collections.Specialized.NameValueCollection();
model.AddParameters.Add("userName", userName);
if (Request.IsAjaxRequest())
return PartialView("UCList", model);
else
return View(model);
}
#endregion
而HTML分页,一般需要一个ASPX文件就可以了,只不能有两种状态,一个是GET状态,一个是POST提交表单的状态,反回到代码中可能是这样的,如:
#region HTML分页和查询
public ActionResult HtmlIndex(int? page)
{
pp = new Entity.PagingParam(page ?? 1, PAGESIZE);
if (!string.IsNullOrEmpty(Request.QueryString["UserName"])) //从URL中获取数据
vp.AddItem("userName", Request.QueryString["UserName"]);
Entity.PagedList<Models.UserBases> model = GetModel(vp, pp);
return View(model);
}
[HttpPost]
public ActionResult HtmlIndex(FormCollection form)
{
pp = new Entity.PagingParam(Convert.ToInt32(form["page"]), PAGESIZE);
if (!string.IsNullOrEmpty(form["UserName"]))//从表单中获取数据
vp.AddItem("userName", form["UserName"]);
Entity.PagedList<Models.UserBases> model = GetModel(vp, pp);
model.AddParameters = new System.Collections.Specialized.NameValueCollection();
model.AddParameters.Add("userName", form["UserName"]);
return View(model);
}
#endregion
看完文单后,你是否是对分页及查询有一个清晰的认识了,呵呵!