0

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?

1
  • You can load a partial view easily enough with jQuery's load() method, but you are already trying to pass back JSON, not HTML. I would instead create a Web API controller, call it with AJAX and return the list of comments for rendering (Web API will take care of the serialization to Json for you). Commented Jun 14, 2014 at 14:14

1 Answer 1

2

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);
 }
});
Sign up to request clarification or add additional context in comments.

2 Comments

But that will return one partial I need to return 10 of them or I am missing something? Comment partial view represent just one comment. I need to return list.
You have to create partial view that accept comment list as a model and when you pass list to that partial view it prepare result for you and return. You can create CommentList PartialView and that internally use your _commentView.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.