chamara
chamara

Reputation: 12709

IPageRetriever not working with Ajax calls

I have the following API call to retrieve page data

 List<VillageNewsItem> newsList = pageRetriever.RetrieveAsync<VillageNewsItem>(
                                          query => query
                                          .Path("/Home/Village-News", PathTypeEnum.Children)
                                          .Published(true)
                                          .OnSite(SiteContext.CurrentSiteName)
                                          .OrderByDescending(x => x.DocumentCreatedWhen)                                          
                                        )?.Result?.ToList();

It works fine and return 2 records if I run the query on page load. Inside Index action of the controller.

public VillageNewsListController(IPageDataContextRetriever dataRetriever, VillageNewsListRepository villageNewsListRepository,
                    IPageRetriever pagesRetriever, IPageDataContextRetriever pageDataContextRetriever, IPageUrlRetriever pageUrlRetriever)
        {
            this._dataRetriever = dataRetriever;
            this._villageNewsListRepository = villageNewsListRepository;
            this._pagesRetriever = pagesRetriever;
            this.pageDataContextRetriever = pageDataContextRetriever;
            this.pageUrlRetriever = pageUrlRetriever;
        }
        

        public async Task<ActionResult> Index(CancellationToken cancellationToken)
        {
            try
            {
               
                    List<VillageNewsItem> newsList = pagesRetriever.RetrieveAsync<VillageNewsItem>(
                                          query => query
                                          .Path("/Home/Village-News", PathTypeEnum.Children)
                                          .Published(true)
                                          .OnSite(SiteContext.CurrentSiteName)
                                          .OrderByDescending(x => x.DocumentCreatedWhen)                                          
                                        )?.Result?.ToList();
                                        
                newsItems.VillageNewsItems = newsList;

                return View(newsItems);
            }
            catch (Exception ex)
            {
                ErrorHandler.EventLog.LogError(ex.Source, ex.Message, ex.StackTrace);
                return RedirectToAction("ErrorPage", "Error");
            }


        }

However, if I try to make the same API call via a client side AJAX call, it doesn't work and return 0 records. Why it's not working with Ajax calls?

Ajax call

function loadMoreNews() {

    $.ajax({
        url: '/VillageNewsList/VillageNewsItemList',
        //data: { "term": request.term },
        type: "POST",
        success: function (data) {
            response($.map(data,
                function (item) {

                    console.log(data);
                }));
        },
        error: function (response) {
            //alert(response.responseText);
        },
        failure: function (response) {
            // alert(response.responseText);
        }
    });

}

Server side method.

[HttpPost]
        [Route("VillageNewsList/VillageNewsItemList")]
        public VillageNewsListViewModel VillageNewsItemList(string NodeAliasPath = "", int villageId = 0, string state = "", int page = 1, int pageSize = 4)
        {
            try
            {
                
                List<VillageNewsItem> newsList = pagesRetriever.RetrieveAsync<VillageNewsItem>(
                                          query => query
                                          .Path("/Home/Village-News", PathTypeEnum.Children)
                                          .Published(true)
                                          .OnSite(SiteContext.CurrentSiteName)
                                          .OrderByDescending(x => x.DocumentCreatedWhen)                                          
                                        )?.Result?.ToList();
                
                var model = new VillageNewsListViewModel
                {
                    VillageNewsItems = newsList, // returns 0 records
                    
                };

                return model;
            }
            catch (Exception ex)
            {
                ErrorHandler.EventLog.LogError(ex.Source, ex.Message, ex.StackTrace);
                //return RedirectToAction("ErrorPage", "Error");
            }

            return null;
        }

Upvotes: 0

Views: 196

Answers (2)

Elmar H&#246;finghoff
Elmar H&#246;finghoff

Reputation: 61

I also asume it is caused by async context here... You can try to use a document query instead. Would be something like this:

var items = new DocumentQuery<VillageNewsItem>(
    .Path("/Home/Village-News", PathTypeEnum.Children)
    .PublishedVersion()
    .Published()
    .OnCurrentSite()
    .OrderByDescending(x => x.DocumentCreatedWhen))
    ?.Result
    ?.ToList();

If you have multiple cultures, add the culture to your query, too.

.Culture(LocalizationContext.CurrentCulture.CultureCode)

Upvotes: 1

Trevor F
Trevor F

Reputation: 1437

Couple things I see.

  1. You're calling IPageRetriever.RetrieveAsync, but you aren't putting an await before it. There may be some odd behavior due to this. Get rid of the ?.Result?.ToList() and instead just put await before it, it will return an IEnumerable of the specified type.
  2. You don't need ".Published" nor "OnSite" with IPageRetriever, this API automatically uses the Current Site Context, the current culture, and either Published or not / Latest Version or not based on if it's in edit/preview mode or not.

See if those things fix the issue!

Upvotes: 1

Related Questions