ASP.NET MVC中有内置的Ajax帮助器,可以覆盖基本方案。
您需要安装和引用
jquery.unobtrusive-ajaxJavascript库(+
jQuery依赖关系)。然后在您的主视图中(假设为index.cshtml)放入以下代码:
Index.cshtml
@Ajax.Actionlink("Load More Posts", "MorePosts", new AjaxOptions(){ HttpMethod = "GET", AllowCache = false, InsertionMode = InsertionMode.InsertAfter, UpdateTargetId = "posts-wrapper"})<div id="posts-wrapper"></div>注意 :
@Ajax.Actionlinkhelper接受
AjaxOptions参数以进行更多定制。
在控制器中(假设为 HomeController.cs ),您应该返回
PartialViewResult:
public ActionResult MorePosts(int? offset, int? count){ IEnumerable<Post> posts = myService.GetNextPosts(offset, count); return PartialView(posts);}最后,您定义 MorePosts.cshtml 部分视图:
@model IEnumerable<Post>@{ Layout = null;}@foreach (var post in Model){ <div > <div>>@post.Prop1</div> <div>@post.Prop2</div> </div> <hr />}就是这样。当某些用户单击
Load More按钮时,将加载更多帖子。
注意1 :您可以实施
OnBegin函数,以实现确定哪些逻辑要加载的实际逻辑的功能(例如,获取最后加载的逻辑的ID并将其发送到服务器)。
注意2
:使用自定义
jQuery.ajax调用(无需jquery.unobtrusive)可以实现相同的结果。唯一的区别是手动ajax调用和click事件。
希望这可以帮助。如果需要,我可以写一个更完整的示例。



