2016-03-14 86 views
1

我對Sitecore和C#很陌生,過去幾天我一直在努力尋找一些東西,所以我希望你們其中一個能夠幫助我。如何獲取Sitecore 7.2中一般鏈接的url路徑C#

我剛剛從Sitecore 6升級到7,並且發生了一些變化。以下代碼用於在Sitecore 6中工作,但獲取LinkField的url的方式不再適用。

protected string writeBalloon(Item targetItem) 
    { 
     string balloonString = ""; 

     Sitecore.Data.Fields.LinkField linkfield = targetItem.Fields["Link"]; 

     balloonString += "<a class='balloon-link' href='" + linkfield.Url + "'>"; 
     balloonString += "<div class='balloon'>"; 

     balloonString += "<h3>"; 
     balloonString += targetItem.Fields["Title"]; 
     balloonString += "</h3>"; 
     balloonString += "<p>"; 
     balloonString += targetItem.Fields["Text"]; 

     balloonString += "</p>"; 
     balloonString += "</div>"; 
     balloonString += "</a>"; 

     return balloonString; 
    } 

我想我已經讀/試圖就此事對谷歌的所有文章,但我似乎仍不能得到它的權利。

回答

0

你需要首先檢查你的鏈接字段類型,使用linkfield.Url僅與Sitecore的外部鏈接類型的作品,這裏是你的代碼應該如何看起來像:

public String LinkUrl(Sitecore.Data.Fields.LinkField lf) 
{ 
    switch (lf.LinkType.ToLower()) 
    { 
     case "internal": 
     // Use LinkMananger for internal links, if link is not empty 
     return lf.TargetItem != null ? Sitecore.Links.LinkManager.GetItemUrl(lf.TargetItem) : string.Empty; 
     case "media": 
     // Use MediaManager for media links, if link is not empty 
     return lf.TargetItem != null ? Sitecore.Resources.Media.MediaManager.GetMediaUrl(lf.TargetItem) : string.Empty; 
     case "external": 
     // Just return external links 
     return lf.Url; 
     case "anchor": 
     // Prefix anchor link with # if link if not empty 
     return !string.IsNullOrEmpty(lf.Anchor) ? "#" + lf.Anchor : string.Empty; 
     case "mailto": 
     // Just return mailto link 
     return lf.Url; 
     case "javascript": 
     // Just return javascript 
     return lf.Url; 
     default: 
     // Just please the compiler, this 
     // condition will never be met 
     return lf.Url; 
    } 
} 



protected string writeBalloon(Item targetItem) 
{ 
     string balloonString = ""; 

     Sitecore.Data.Fields.LinkField linkfield = targetItem.Fields["Link"]; 

     balloonString += "<a class='balloon-link' href='" + LinkUrl(linkfield) + "'>"; 
     balloonString += "<div class='balloon'>"; 

     balloonString += "<h3>"; 
     balloonString += targetItem.Fields["Title"]; 
     balloonString += "</h3>"; 
     balloonString += "<p>"; 
     balloonString += targetItem.Fields["Text"]; 

     balloonString += "</p>"; 
     balloonString += "</div>"; 
     balloonString += "</a>"; 

     return balloonString; 
} 

Note:本取供LinkUrl代碼段()方法從該Answer

+0

非常感謝您的快速回復。像魅力一樣工作! :) –

4

採取自Sitecore的7.2,一種方法GetFriendlyUrl()加入到LinkField類來解決這個問題。

Sitecore.Data.Fields.LinkField linkfield = targetItem.Fields["Link"]; 
var url = linkfield.GetFriendlyUrl(); 

GeneralLink in Sitecore