.NetMvc之支持搜索+排序的AjaxPager分页
在.NET MVC中实现支持搜索和排序的Ajax分页,你可以使用Ajax.BeginForm来提交表单并更新页面内容,而不是重新加载整个页面。以下是一个简化的例子:
- 视图(View)中的Ajax表单和分页逻辑:
@using (Ajax.BeginForm("ActionName", "ControllerName", new AjaxOptions {
HttpMethod = "GET",
UpdateTargetId = "content",
InsertionMode = InsertionMode.Replace
}))
{
<input type="text" name="search" value="@ViewBag.Search" />
<input type="hidden" name="sort" value="@ViewBag.Sort" />
<input type="hidden" name="page" value="@ViewBag.Page" />
<input type="submit" value="Search" />
}
<div id="content">
<!-- 这里将显示查询结果 -->
</div>
<nav>
<ul class="pagination">
@for (int i = 1; i <= ViewBag.TotalPages; i++)
{
<li class="@(i == ViewBag.Page ? "active" : "")">
@Ajax.ActionLink(i.ToString(), "ActionName", "ControllerName", new { page = i, sort = ViewBag.Sort, search = ViewBag.Search }, new AjaxOptions { UpdateTargetId = "content", InsertionMode = InsertionMode.Replace })
</li>
}
</ul>
</nav>
- 控制器(Controller)中处理请求的逻辑:
public ActionResult ActionName(int? page, string sort, string search)
{
int currentPage = page ?? 1;
var itemsPerPage = 10;
var items = GetItems(search); // 获取项的方法,可能会根据搜索条件来查询数据库
var viewModel = new PaginationViewModel
{
Items = items.OrderBy(sort).ToPagedList(currentPage, itemsPerPage),
Page = currentPage,
TotalPages = items.PageCount,
Sort = sort,
Search = search
};
return PartialView("_PartialViewName", viewModel);
}
private IEnumerable<Item> GetItems(string search)
{
// 模拟数据库查询
var items = new List<Item>
{
// ...
};
if (!string.IsNullOrEmpty(search))
{
items = items.Where(i => i.Name.Contains(search)).ToList();
}
return items;
}
- 分页视图模型:
public class PaginationViewModel
{
public IPagedList<Item> Items { get; set; }
public int Page { get; set; }
public int TotalPages { get; set; }
public string Sort { get; set; }
public string Search { get; set; }
}
确保你已经安装了PagedList.Mvc包,这样你才能使用ToPagedList
扩展方法。
这个例子展示了如何使用Ajax.
评论已关闭