ASP.NET MVC中有内置的Ajax助手程序,可以处理基本场景。
您需要安装并引用jquery.unobtrusive-ajax
JavaScript库(需要依赖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.ActionLink
助手接受 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 class="post">
<div>>@post.Prop1</div>
<div>@post.Prop2</div>
</div>
<hr />
}
就是这样,当某个用户点击“加载更多”按钮时,将会加载更多的文章。
注意1:您可以实现OnBegin
函数来实现实际逻辑,以决定要加载哪些文章(例如,获取已加载文章的最后一个ID并将其发送到服务器)。
注意2:可以使用自定义的jQuery.ajax
调用(而不是jquery.unobtrusive),来实现相同的结果。唯一的区别是手动设置ajax调用和点击事件。
希望这有所帮助。如果需要,我可以撰写更完整的示例。
我建议从NUGET获取Westwind.Web.Mvc
库,您可以将任何视图运行为字符串,以作为JSON结果返回。
public JsonResult GetPosts()
{
string postsHtml = ViewRenderer.RenderPartialView("~/views/yourcontroller/_PostsPartial.cshtml",model);
return Json(new { html = postsHtml });
}
return PartialView(model)
从MVC控制器简单地返回部分视图。但是,使用RenderPartialView,您可以将其作为字符串获取,如果需要,可以与任何其他值一起输出为JSON格式。如果选择使用WebAPI,这将起作用,因为它没有渲染视图的能力。
$.load
调用控制器方法返回partialview
,并返回部分视图名称"_PartialViewName"
的部分视图。 - Guruprasad J Raoajax
,只需使用$.load
。 - Guruprasad J Rao