如何使用AJAX加载在html中呈现的完整局部视图(所以我只设置了div.html)
我需要ajax调用来调用控制器动作,该动作将呈现完整的局部视图(红色)并将其附加到当前加载的视图的末尾?
[我知道如何附加到DOM以及如何进行AJAX调用]
我需要知道什么是最好的管道方法,操作返回的ActionResult类型和如果已经内置这个机制所以要避免重新发明轮子?
答案 0 :(得分:22)
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 />
}
就是这样。当某些用户点击Load More
按钮时,会加载更多帖子。
注1 :您可以实现OnBegin
函数来实现用于决定下一个要加载的帖子的实际逻辑(例如,获取上次加载的帖子的ID并发送它到服务器)。
注意2 :使用自定义jQuery.ajax
调用(没有jquery.unobtrusive)可以获得相同的结果。唯一的区别是手动ajax调用和点击事件。
希望这会有所帮助。如果需要,我可以写一个更完整的例子。
答案 1 :(得分:2)
我建议从NUGET获取Westwind.Web.Mvc
库,然后您可以将任何视图运行到字符串以作为JSON结果返回
public JsonResult GetPosts()
{
string postsHtml = ViewRenderer.RenderPartialView("~/views/yourcontroller/_PostsPartial.cshtml",model);
return Json(new { html = postsHtml });
}
正如@Guruprasad在评论中所说,您可以使用return PartialView(model)
简单地从MVC控制器返回部分视图,但是使用RenderPartialView,您可以将其作为字符串输出,您可以将其作为JSON以及任何其他输出值如果需要。如果您选择使用WebAPI,这将有效,因为它无法呈现内置视图。