How to choose and show a random document on the website

Danuta Welz asked on December 5, 2017 15:51

How to choose and show a random document on the website (eg News).

I am able to display a list of documents using the Custom Zone and querry on the website

Code

var documents = CMS.DocumentEngine.DocumentHelper.GetDocuments ("CMS.News")                                        .Path ( "/ news /%")                                        .OnSite ("SiteName ')                                        .OrderBy ("DocumentName ')                                        .WhereGreaterThan ("NewsReleaseDate", DateTime.Now.AddDays (-300));

Code

I want to choose some of the latest News and one random one. Is it possible?

Recent Answers


Peter Mogilnitski answered on December 5, 2017 17:24 (last edited on December 5, 2017 21:18)

The document helper does not have such a method. Although can do it with sql query. Just to give you an idea, you use something like this below:

WITH ValidNews AS
(
    select ROW_NUMBER() OVER (ORDER BY NewsId) AS RowNumber, * 
    from CONTENT_News 
    WHERE NewsReleaseDate > DATEADD(year, -1, GetDate()) 
) 
select * from validnews  where rownumber <= 3
UNION
select * from (select top 1 * from validnews where  rownumber > 3 order by NEWID()) Random
0 votesVote for this answer Mark as a Correct answer

Brenden Kehren answered on December 6, 2017 15:13 (last edited on December 7, 2017 18:17)

In your DocumentQuery you can add .OrderBy(Guid.NewGuid()) and this should resolve your issue of getting something randomly. Also make sure your caching is not set real high otherwise it will cache the results and you won't see a random one until the cache clears.

0 votesVote for this answer Mark as a Correct answer

Peter Mogilnitski answered on December 7, 2017 18:05

There is random document web part as well and you can do something like this

0 votesVote for this answer Mark as a Correct answer

   Please, sign in to be able to submit a new answer.