我在ASP.NET MVC 5中有一个列表。
我限制了每页显示的记录数。
现在,当我滚动时,我会进行Ajax调用。第一次调用很好,但是当我向下滚动更多时,它会重复调用函数5到10次,并再次丢失显示数据,这真的很奇怪,我找不到解决方案。
我的控制器:
public ActionResult Index()
{
int starting = 0;
if (Request.Form["starting"] != null)
{
starting = Convert.ToInt32(Request.Form["starting"]);
}
int takes = 15;
if (Request.Form["takes"] != null)
{
takes = Convert.ToInt32(Request.Form["takes"]);
}
//string strpost = "&ajax=1";
var query = db.MyEmployee.ToList().Skip(starting).Take(takes);
if (Request.IsAjaxRequest())
{
starting = starting+15;
query = db.MyEmployee.ToList().Skip(starting).Take(takes);
ViewData["starting"] = starting;
ViewBag.takes = takes;
return PartialView("_PartialIndex",query);
}
ViewBag.starting = starting;
ViewBag.takes = takes;
return View(query);
}
我的模型:
public class Employee
{
public int Id { get; set; }
public string FullName { get; set; }
public string Email { get; set; }
}
我的视图和部分视图代码:
<div id="mypage">
@model IEnumerable<MVC5WAuth.Models.Employee>
@{
ViewBag.Title = "Index";
}
<h2>Index 1</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Id)
</th>
<th>
@Html.DisplayNameFor(model => model.FullName)
</th>
<th>
@Html.DisplayNameFor(model => model.Email)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Id)
</td>
<td>
@Html.DisplayFor(modelItem => item.FullName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Email)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.Id }) |
@Html.ActionLink("Details", "Details", new { id = item.Id }) |
@Html.ActionLink("Delete", "Delete", new { id = item.Id })
</td>
</tr>
}
</table>
<script type="text/javascript">
$(window).scroll(function () {
if ($(window).scrollTop() == $(document).height() - $(window).height()) {
// ajax call get data from server and append to the div
var ajax_image = "<img src='../Content/loading.GIF' >";
$('#mypage').html(ajax_image);
var params = '&starting=' + @ViewBag.starting + '&takes=' + @ViewBag.takes;
$.ajax({
url:'@Url.Action("Index", "Employees")',
type: "POST",
data: params,
})
.done(function (r) {
$('#mypage').html(r);
});
}
});
</script>
ViewBag
将永远不会更新,因为它不会作为AJAX调用的一部分重新加载。我建议在JS中持久化一个变量,您可以在每个AJAX调用上递增它。 - Chris Pickford@ViewBag.starting
和@ViewBag.takes
,它们是在第一次生成视图时的初始值(仅因为你在方法中再次设置它们并不会更新它们)。你需要将这些值作为 JavaScript 变量来维护,并对它们进行递增。 - user3559349Index.cshtml
视图吗?(这可以解释这种行为) - user3559349