How to render partial view in MVC5 via ajax call to a controller and return HTML
Solution 1:
There is built-in ajax helpers in ASP.NET MVC which can cover the basic scenarios.
You need to install and refer jquery.unobtrusive-ajax
JavaScript library ( + jQuery dependency). Then in your main view (let's say index.cshtml) put following code:
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>
Note: @Ajax.ActionLink
helper accepts AjaxOptions
parameter for more customizations.
In the controller (let's say HomeController.cs) you should return PartialViewResult
:
public ActionResult MorePosts(int? offset, int? count)
{
IEnumerable<Post> posts = myService.GetNextPosts(offset, count);
return PartialView(posts);
}
Finally you define the MorePosts.cshtml partial view:
@model IEnumerable<Post>
@{
Layout = null;
}
@foreach (var post in Model)
{
<div class="post">
<div>>@post.Prop1</div>
<div>@post.Prop2</div>
</div>
<hr />
}
And that's it. When some user clicks on Load More
button, more posts will be loaded.
Note 1: you can implement OnBegin
function to implement the actual logic for deciding which are the next posts to load (ex. get the id of the last loaded post and send it to the server).
Note 2: the same result can be achieved with custom jQuery.ajax
calls (without jquery.unobtrusive). The only differences will be the manual ajax calls and click events.
Hope this helps. I can write a more complete example if needed.
Solution 2:
I recommend getting the Westwind.Web.Mvc
library from NUGET and you can run any of your views to a string to return back as a JSON result
public JsonResult GetPosts()
{
string postsHtml = ViewRenderer.RenderPartialView("~/views/yourcontroller/_PostsPartial.cshtml",model);
return Json(new { html = postsHtml });
}
As @Guruprasad said in the comments, you can simply return back a partial view from an MVC controller using return PartialView(model)
, but with the RenderPartialView you get it as a string that you can output as JSON along with any other values if required. This will work if you choose to use WebAPI, because it doesn't have the ability to render a view built in.