以下代码在http://www.keelycattschoolofdance.co.uk主页上显示了一个推荐项目,效果很好:
@using umbraco.MacroEngines;
@inherits umbraco.MacroEngines.DynamicNodeContext
@{
var numberOfItems = 1;
DynamicNodeList pages = @Model.Children.Where("umbracoNaviHide != true").Take(numberOfItems).OrderBy("UpdateDate");
}
<div>
@foreach (DynamicNode page in pages)
{
<h2>@page.Name</h2>
<p>@page.GetProperty("introText")</p>
<p><a href="@page.Url">Read more...</a></p>
<p><strong>@page.GetProperty("personsName")</strong></p>
}
</div>
我想通过选择随机推荐来进一步采用这个小脚本。我应该怎么做呢?
答案 0 :(得分:4)
试
var r = new Random();
var numberOfItems = 1;
List<DynamicNode> pages = new DynamicNode(Model.Id).Descendants().Items.Where(x => x.Visible).OrderBy(x => r.Next()).Take(numberOfItems).ToList();
答案 1 :(得分:3)
我更喜欢使用Linq生成随机元数据然后按它排序的方法。
IPublishedContent containerNode = Umbraco.TypedContent(1144);
IPublishedContent randomlySelectedChildNode = containerNode.Children.OrderBy(n => Guid.NewGuid()).FirstOrDefault();
您还可以使用内置的Umbraco扩展程序:
var randomNode = containerNode.Children.RandomOrder().FirstOrDefault();
答案 2 :(得分:0)
尝试 ElementAt ()Linq方法:
Random r = new Random();
int max = 10; // set your own max
var items = @Model.Content.AncestorOrSelf(1).Descendants("SomeNode").First().Descendants("SomeChildNode").First().Children;
var item = items.ElementAt(r.Next(0, max)); // use linq ElementAt to retrieve your random node