1

I have four zones(Default, Intranet, Internet and Extranet) configured for my web application. Each zone is having different URL. I am developing a web part which needs to display the links to the News Archieve and my aim is to display the Latest News. What would be the best to get the relative URL of the news item and to avoid the broken link in the webparts for each zone? I am using the following code which is blindly getting the Site URL(which is my default Zone URL).

 NewsHelper helper = new NewsHelper();
        List<LatestNewsItem> newsList = new List<LatestNewsItem>();           
        using (SPSite site = new SPSite(SiteUrl))            
        {
            using (SPWeb web = site.OpenWeb())
            {
                SPList list = web.Lists.TryGetList(ListName);
                if (list != null)
                    newsList = helper.GetLatestNews(list);
            }
        }
1

Within a web part, you can use the SPContext to get access to the SPSite and SPWeb objects by Guid without having to hard-code a URL:

Guid siteId = SPContext.Current.Site.ID;
Guid webId = SPContext.Current.Web.ID;
using (SPSite site = new SPSite(siteId))            
{
    using (SPWeb web = site.OpenWeb(webId))
    {
        SPList list = web.Lists.TryGetList(ListName);
        if (list != null)
            newsList = helper.GetLatestNews(list);
    }
}

That said, are you manually rendering links to the items in the list? Because the default zone URL will resolve on the server, your code will work even with that URL in the constructor.

If you are manually rendering links to items in lists, just make sure you're using the server-relative URL properties. For instance, the server-relative URL of the display form of an SPListItem would be:

string.Format("{0}?ID={1}", item.ParentList.Forms[PAGETYPE.PAGE_DISPLAYFORM].ServerRelativeUrl, item.ID);
1

If your SiteUrl property is an url of other site collection (that does not contain your web part) you can try to resolve your issue like this.

using (SPSite site = new SPSite(SiteUrl))            
{
     using (SPSite newsSite = new SPSite(site.ID, SPContext.Current.Site.Zone))
     {
         using (SPWeb web = newsSite.OpenWeb())
         {
                SPList list = web.Lists.TryGetList(ListName);
                if (list != null)
                    newsList = helper.GetLatestNews(list);
         }
     }
}

in other case you can use SPContext.Current.Site.ID to retrieve id of the current site.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.