0

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;
        }
Ken White
  • 123,280
  • 14
  • 225
  • 444
chamara
  • 12,649
  • 32
  • 134
  • 210
  • I think the site context might be missing or that the culture might be different or something. Can you check in debugging what the value of 'SiteContext.CurrentSiteName' is and if the culture is different in the two calls? – A. van Hugten Dec 20 '22 at 09:08

2 Answers2

1

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!

Trevor F
  • 1,429
  • 9
  • 6
  • Trevor is right - don't use async + `.Result`. Async/`Task` should bubble up through your entire app to the top (Controller/Action). It's also worth mentioning that if you are using localization, the request context is not automatically populated with the culture on XHR/Fetch requests. Checkout my blog post, which covers this topic https://dev.to/wiredviews/bits-of-xperience-localizing-xhr-requests-in-kentico-xperience-13-0-4i3j – seangwright Dec 19 '22 at 22:00
  • I tried the suggested fix but didn't work unfortunately. – chamara Dec 19 '22 at 23:34
0

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)