Reputation: 6829
I have a div that is loaded with list of partials:
@foreach (var comment in Model.Comments)
{
Html.RenderPartial("~/Views/Comment/_CommentView.cshtml", comment);
}
When user scrolls down to the bottom of the page I load new comments in that div:
public ActionResult LoadMore(int pageIndex)
{
int _pageSize = 10;
var model = ... get comments
return Json(model.ToList(), JsonRequestBehavior.AllowGet);
}
In page jquery function I add new comments like
for (var i = 0; i < response.length; i++) {
ctrls.push("<div class='comment'> <h4>" +"response[i].CommentText" + "</h4></div>");
}
But this code is not reusable at all so I want to make it better.
Is it possible to:
1) Somehow render partial in JS function and pass data in?
2) Return list of partials from ActionMethod and just add it from JS function?
Upvotes: 0
Views: 2831
Reputation: 17485
You definitely return PartialView result from Controller Method. In that case you have to return partial view instead of JSON. That partial view directly contain html to render so in success method of ajax call add it to your container.
public ActionResult LoadMore(int pageIndex)
{
int _pageSize = 10;
var model = ... get comments
return Partial("Comment" , model);
}
Ajax Call
$.ajax({
url: '' // set as your wish
data: // pageIndex
success : function(data){
$('#commentContainer').append(data);
}
});
Upvotes: 2