Search code examples
c#ajaxasp.net-mvceditorfor

Asp.Net MVC Editor Template and Infinite Scrolling


I have following Editor Template for a Table Data as MyProjectViewModel.cshtml

<div>
    <div>
        @Html.CheckBoxFor(model => model.Selected)
    </div>
    <div>
            for (int i = 1; i < @Model.TypeList.Count; i++)
            {
                    <p id="@Model.TypeList[i].ID" >@Model.TypeList[i].Name</p>
            }
    </div>
        @Html.HiddenFor(model => model.ID)
        @Html.HiddenFor(model => model.Name)
</div>

And I have another view where it is used to post the selected Item, which has the following statement to render the editor template.

<div id="loadDynamic">
@Html.EditorFor(model => model.NewItem)
</div>

If i post i am able to get the selected items.

However now I have an issue because this data has to render dynamically on a button click. Onload I will be populating the first 10 items and displaying using the editor Template.

However I am stuck how can I get the next 10 data using Ajax and append as part of the above Editor Template.

I have created following Action and Ajax however it does't seem to be the proper one.

Action:

public ActionResult InfinateScroll(string lastID, string prjID)
{
   //Querying DB to get List<Model>
   //Not sure how to get the Editor Template here
   // Tried with following, though it is not the one I needed
   return Json(PartialView("~/Views/MyView/EditorTemplates/MyProjectViewModel.cshtml", model[0]));
}

Ajax:

$a.ajax({
                type: "POST",
                url: '@Url.Action("InfinateScroll", "Project")',
                data: values,
                traditional: true,
                dataType: 'html',
                cache: false,
                success: function (data) {
                    $("#loadDynamic").append(data);
                    $("#loadingDiv").hide();
                },
});

Here even if I am able to append how likely that I will get both the previously selected items and the new one while posting. Please guide me.


Solution

  • The only problem I see with the code you've provided is that you're trying to return the partial view as JSON. Remove the call to Json, and just return PartialView(...). Then, you should be golden.

    As far as not returning duplicates goes, you need to treat this as an actual pager. Infinite scrolls don't just return 10 new random items, they page the data without using paging links. So, when you send your AJAX request, you'll need to pass along the current "page" you're on, and use that determine how to dice the data for the return. You can do it manually easily enough using LINQ helpers like Skip and Take, but you may find it easier to employ a third-party library like PagedList. It's up to you.