How to bind link items to a Repeater in Sitecore

2019-09-09 20:57发布

The content tree is as follows:

content
 -News Listing
  -Article1
  -Article2
  -Article3

Each of the Articles is of a Data Template - "News Article" which is as:

News Article
  Article --(Field section)
    Related Articles --(Multilist - with datasource as '/content/News Listing')

Each article has the other 2 articles as its 'Related Articles'. For eg: Article1 has related articles 2&3 and so on.

Markup:

<h3>Related articles</h3>
<asp:Repeater ID="rpArticles" runat="server" ItemType="Sitecore.Data.Items.Item">
 <HeaderTemplate>
    <ul class="relatedArticles">
 </HeaderTemplate>
 <ItemTemplate>
    <li>
      <sc:Link Field="<%#Item.Paths.FullPath %>" runat="server" Item="<%#Container.DataItem %>">
          <sc:Text Field="Heading" runat="server"/>
      </sc:Link>         
    </li>                                
 </ItemTemplate>
 <FooterTemplate>
    </ul>
 </FooterTemplate>
</asp:Repeater>

Code:

private void Page_Load(object sender, EventArgs e)
 {
   MultilistField relatedArticles = Sitecore.Context.Item.Fields["Related Articles"];
   rpArticles.DataSource = relatedArticles.TargetIDs.Select(id => Sitecore.Context.Database.GetItem(id));
   rpArticles.DataBind();
 }

The above markup is a solution from Here
'Heading' is the name of the field (eg: Article1, Article2 etc..)

When I browse 'News Article 1', the related articles should be 2 & 3, but the output is incorrect & also no anchor tags. Just plain text.

What is wrong in my code.

output:

Related Articles
Article1
Article1

2条回答
贼婆χ
2楼-- · 2019-09-09 21:34

Not sure why you changed your original question since it was almost correct. Since the item you are linking to is not specified in a General Link field you cannot use an sc:Link control, instead is far simpler to either use an ASP.Net Hyperlink control which is bound from code behind in the Item_Bound event or simply append the Item URL to an anchor link:

<ItemTemplate>
    <li>
        <a href="<%# Sitecore.Links.LinkManager.GetItemUrl((Sitecore.Data.Items.Item) Container.DataItem) %>">
            <sc:Text Field="Heading" runat="server" Item="<%#Container.DataItem %>"/>
        </a>
    </li>                                
</ItemTemplate>
查看更多
爷的心禁止访问
3楼-- · 2019-09-09 21:43

My original answer was wrong as pointed out in comments. Snap response without thinking fully, sorry! Correction:

You're populating the Sitecore text field with the current context item's Header field. Instead your sc:Text control needs to set its Field property from the Container.DataItem.

So try replacing...

<sc:Text Field="Heading" runat="server"/>

...with...

<sc:Text Field="Heading" runat="server" Item="<%# Container.DataItem %>"/>
查看更多
登录 后发表回答