我在控制器中有2个方法。第一种方法是List,主视图,我只是尝试实现分页和导航。
public ActionResult List(string category, int page = 1)
{
ListViewModel model = new ListViewModel
{
Fields = new List<SelectListItem>
{
new SelectListItem { Text = "Order By Descending", Value = "OrderByDescending" },
new SelectListItem { Text = "Order By Ascending", Value = "OrderByAscending" },
},
Furnitures = repository.Furnitures
.Where(p => category == null || p.Category.Name == category)
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ToList(),
InfoPages = new InfoPage
{
CurrentPage = page,
ItemsPerPage = pageSize,
TotalItems = category == null ? repository.Furnitures.Count() :
repository.Furnitures.Where(furniture => furniture.Category.Name == category).Count()
},
CurrentCategory = category,
};
return View(model);
}
第二个方法是Summary(用于局部视图),我用ajax实现排序并返回带有好东西的PartialView
public ActionResult Summary(string SelectedValue)
{
ViewBag.CurrentSort = SelectedValue;
IEnumerable<Furniture> result = repository.Furnitures;
if (SelectedValue != null)
{
if (SelectedValue.Equals("OrderByDescending"))
{
result = repository.Furnitures.OrderBy("Price desc").ToList();
}
else if (SelectedValue.Equals("OrderByAscending"))
{
result = repository.Furnitures.OrderBy("Price asc").ToList();
}
else
{
result = repository.Furnitures.OrderBy("FurnitureId").ToList();
}
}
return PartialView(result);
}
所以Ajax运行良好,它很好地分类我的好东西,但现在所有的好东西列表显示在一个页面,如果我去第二页,我看到相同的列表。所以我的分页现在不起作用,这里我是如何在View
中实现分页的@Html.PageLinks(Model.InfoPages, x => Url.Action("List", "Furniture", new { page = x, category = Model.CurrentCategory }))
我尝试将Skip()
和.Take()
添加到我的结果变量中,但分页仍然不起作用,我的代码有什么问题?
更新: 我打电话给摘要视图
<div class="container" id="tableBody" >
@Html.Action("Summary")
</div>
Ajax.BeginForm()调用next
@using (Ajax.BeginForm("Summary", "Furniture", null, new AjaxOptions
{
HttpMethod = "GET",
UpdateTargetId = "tableBody",
Confirm = "Confirm AJAX-request?",
InsertionMode = InsertionMode.Replace
}))
{
@Html.DropDownListFor(x => x.SelectedValue, new SelectList(Model.Fields, "Value", "Text", Model.SelectedValue), "-- Select Product--")
<input type="submit" value="Update" />
}
Html.PageLinks它的html帮助器,它的类MvcHtmlString(我按照Adam Freeman书中描述的教程“Pro Asp.Net Mvc 5”中描述了导航)
答案 0 :(得分:0)
更改此行
@Html.PageLinks(Model.InfoPages, x => Url.Action("List", "Furniture", new { page = x, category = Model.CurrentCategory }))
的
@Html.PageLinks(Model.InfoPages, x => Url.Action("List", "Furniture", new { page = Model.InfoPages.CurrentPage, category = Model.CurrentCategory }))
你的Action期望参数页面为Int,你发送的是一个转换为字符串的InfoPage类。
x.CurrentPage它实际上是你当前的页面,所以你应该改变你想要显示的页面(例如x.CurrentPage + 1?x.CurrentPage-1?)
此外,我鼓励您使用现有的网格或组件来解决这类视图,因为在其他情况下,您将不得不在需要分页的每个视图上重新实现。
一个很好的开源网格,用于解析ajax:http://mvc-grid.azurewebsites.net/