我正在尝试使用ajax在mvc项目中实现加载更多数据功能。所以我遵循了这种方法: https://www.codeproject.com/Articles/1043142/Implementing-Load-More-Button-using-ASP-NET-MVC-an
一切似乎都很好,但是当我第一次点击加载更多数据按钮时它会点击控制器,但会显示最初加载的相同数据。然后当我再次点击按钮时,它甚至没有打到控制器让我调试,它再次显示相同的初始数据。顺便说一句,控制台没有错误。这是我的控制器:
public ActionResult Index()
{
var model = new HomePageViewModel
{
InitiallyLoadedPosts = _postService.GetAllPosts(new GetPostsInput { IsPublished = true, ReturnCount = 4 })
};
return View(model);
}
[HttpPost]
[AllowAnonymous]
public JsonResult LoadMorePost(int size)
{
var model = new LoadMorePostsViewModel { Posts = _postService.GetAllPosts(new GetPostsInput { IsPublished = true, SkipCount = size, ReturnCount = 4 }) };
int modelCount = model.Posts.Count();
if (model.Posts.Any())
{
string modelString = RenderRazorViewToString("_LoadMorePost", model);
return Json(new { ModelString = modelString, ModelCount = modelCount });
}
return Json(model, JsonRequestBehavior.AllowGet);
}
public string RenderRazorViewToString(string viewName, object model)
{
ViewData.Model = model;
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,
viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View,
ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}
这是我的索引HTML
@foreach (var post in Model.LoadMorePosts.Batch(4))
{
foreach (var subPost in post)
{
<article class="cb-blog-style-b cb-module-a cb-article cb-article-row-2 cb-article-row cb-img-above-meta clearfix cb-separated @(cssClass) post type-post status-publish format-video has-post-thumbnail hentry category-design">
// data binding
</article>
}
}
<a id="loadMore" href="#">Load More</a>
// string rendered view :
@foreach (var post in Model.Posts)
{
<article class="cb-blog-style-b cb-module-a cb-article cb-article-row-2 cb-article-row cb-img-above-meta clearfix cb-separated cb-no-2 post-111 post type-post status-publish format-video has-post-thumbnail hentry category-design tag-food tag-health tag-lorem tag-vintage post_format-post-format-video">
// string rendered view.
</article>
}
这是我的Ajax调用
(function () {
$(function () {
var loadCount = 1;
$("#loadMore").on("click", function (e) {
e.preventDefault();
$.ajax({
url: Url.Action("LoadMorePost", "Home"),
data: { size: loadCount * 4 }.serialize(),
cache: false,
type: "POST",
success: function (data) {
if (data.length !== 0) {
$(data.ModelString).insertBefore("#loadMore").hide().fadeIn(2000);
}
var ajaxModelCount = data.ModelCount - (loadCount * 4);
if (ajaxModelCount <= 0) {
$("#loadMore").hide().fadeOut(2000);
}
},
error: function (xhr, status, error) {
console.log(xhr.responseText);
alert("message : \n" + "An error occurred, for more info check the js console" + "\n status : \n" + status + " \n error : \n" + error);
}
});
loadCount = loadCount + 1;
});
});
})();
任何帮助都将不胜感激。