Getting a usable SPItem URL to a display form
This is definitely from the "I can't believe I hadn't blogged this already department".
When you try to use the SPListItem.Url property you wind up getting a url that's relative to the site (even though it starts with a '/').
I've written this method that will return a list item url and takes into account the fact that the urls differ when they're lists or document libraries:
private string GetItemUrl(SPListItem listItem)
{
string result;
string itemUrlTemp = listItem.Url.Replace("Lists/", "");
string siteRelativeListUrl = itemUrlTemp.Substring(0, itemUrlTemp.IndexOf('/'));
if (listItem.ListItems.List.BaseTemplate == SPListTemplateType.DocumentLibrary)
result = SPEncode.UrlEncodeAsUrl(String.Format("{0}/{1}/Forms/Dispform.aspx?ID={2}", listItem.ListItems.List.ParentWeb.Url, siteRelativeListUrl, listItem.ID));
else
result = SPEncode.UrlEncodeAsUrl(String.Format("{0}/Lists/{1}/Dispform.aspx?ID={2}", listItem.ListItems.List.ParentWeb.Url, siteRelativeListUrl, listItem.ID));
return result;
}
When you try to use the SPListItem.Url property you wind up getting a url that's relative to the site (even though it starts with a '/').
I've written this method that will return a list item url and takes into account the fact that the urls differ when they're lists or document libraries:
private string GetItemUrl(SPListItem listItem)
{
string result;
string itemUrlTemp = listItem.Url.Replace("Lists/", "");
string siteRelativeListUrl = itemUrlTemp.Substring(0, itemUrlTemp.IndexOf('/'));
if (listItem.ListItems.List.BaseTemplate == SPListTemplateType.DocumentLibrary)
result = SPEncode.UrlEncodeAsUrl(String.Format("{0}/{1}/Forms/Dispform.aspx?ID={2}", listItem.ListItems.List.ParentWeb.Url, siteRelativeListUrl, listItem.ID));
else
result = SPEncode.UrlEncodeAsUrl(String.Format("{0}/Lists/{1}/Dispform.aspx?ID={2}", listItem.ListItems.List.ParentWeb.Url, siteRelativeListUrl, listItem.ID));
return result;
}
Comments