我在ASP.NET MVC中使用分页,但是导航到下一页时丢失了模型数据。
代码如下:
局部视图:
@using PagedList;
@using PagedList.Mvc;
@model Models.MyObject
<link href="~/Content/PagedList.css" rel="stylesheet" type="text/css" />
<table class="table table-striped table-hover sortable">
<thead>
<tr>
<th width="240">@Model.HeaderNames[0]</th>
<th width="240">@Model.HeaderNames[1]</th>
<th width="240">@Model.HeaderNames[2]</th>
<th width="240">@Model.HeaderNames[3]</th>
<th width="120" class="no-sort"></th>
</tr>
</thead>
<tbody>
@foreach (var member in Model.PagedModelList)
{
<tr>
<td><span class="sort-field-value">@member.Thead1</span></td>
<td><span class="sort-field-value">@member.Thead2</span></td>
<td><span class="sort-field-value">@member.Thead3</span></td>
<td><span class="sort-field-value">@member.Thead4</span></td>
</tr>
}
</tbody>
</table>
<footer>
<div>
Page @(Model.PagedModelList.PageCount < Model.PagedModelList.PageNumber
? 0 : Model.PagedModelList.PageNumber) of @Model.PagedModelList.PageCount
@Html.PagedListPager(Model.PagedModelList, page =>Url.Action("Reports",new { @page = page, FirstLoad = false }))
</div>
</footer>
控制器:
public ActionResult Reports(MyObject model, int? page, bool FirstLoad = true)
{
model.pageSize = 4;
model.pageNumber = (page ?? 1);
if (FirstLoad)
{
// getting the data from database here
// ... code
// assigning pagemodelist
model.PagedModelList = model.ModelList.ToPagedList(model.pageNumber, model.pageSize);
}
// here sending the model and all is good
return PartialView("_MyView", model);
}
模型
public class MyObject
{
public int SelectedPeriod { get; set; }
public List<SecondObject> ModelList = new List<Secondobject>();
public IPagedList<Secondobject> PagedModelList ;
public int pageSize { get; set; }
public int pageNumber { get; set; }
}
第二个模型类:
public class SecondObject
{
public string Thead1 { get; set; }
public string Thead2 { get; set; }
public string Thead3 { get; set; }
public string Thead4 { get; set; }
}
预计将获得下一页,但我得到的只是一个空模型,当再次从控制器发送视图时会导致空引用。我在这里做错了什么?
我第一次在模型中获取正确的数据,显示带有正确数据的表,然后单击下一页时,我在控制器中进行调试,因此我得到了空model.PagedModelList
,甚至还有一些其他空模型属性
任何帮助表示赞赏
答案 0 :(得分:0)
也许,尝试通过以下参数传递模型:
@Html.PagedListPager(Model.PagedModelList, page =>Url.Action("Reports",new {@model = Model, @page = page, FirstLoad = false }))
编辑: 另一个解决方案是从参数中删除MyObject。 每次从数据库加载数据。您可以按照以下示例 GitHub project