7

I need to have an absolute URL of a listitem's display form - currently I do it the following way:

On http://example.com/:

item.ParentList.ParentWeb.Url.TrimEnd('/') //"http://example.com"
+ "/" 
+ item.ParentList.DefaultDisplayFormUrl.Trim('/')//"Lists/WorkflowTasks/DispForm.aspx"
+ "?ID=" + item.ID //"?ID=1"

This gets me the correct URL, meaning http://example.com/Lists/WorkflowTasks/DispForm.aspx?ID=1.

However this fails when my site collection is on a slightly more sophisticated host url, for example http://example.com/sites/secondsite/ - both methods from my code return the url containing the "/sites/secondsite/ part so I end up with http://example.com/sites/secondsite/sites/secondsite/Lists/etc...

How do I code it in a more reliable way?

3 Answers 3

16

There are a couple of methods for this available in the object model without the need to handle the slashes etc yourself, one method using MakeFullUrl:

var fullUrl = item.ParentList.ParentWeb.Site.MakeFullUrl(item.ParentList.DefaultDisplayFormUrl);

Parameters

strUrl

Type: System.String

A string that specifies the server-relative URL.

Return value Type: System.String

A string that contains the full URL.

3
  • 3
    You forgot to add + "?ID=" + item.ID at the end to fulfill OP's request. Commented Jun 1, 2015 at 12:33
  • yes you have to add id to this then it gives us 100% result as we want
    – Madhav
    Commented Apr 19, 2016 at 10:53
  • var itemId = "?ID=" + item.ID; var fullUrl = item.ParentList.ParentWeb.Site.MakeFullUrl(item.ParentList.DefaultDisplayFormUrl + itemId);
    – Madhav
    Commented Apr 19, 2016 at 10:54
2
var parentWebUrl = item.ParentList.ParentWebUrl;
var displayFormUrl = item.ParentList.DefaultDisplayFormUrl;
var itemIdQuery = "?ID=" + item.ID;
var fullUrl = parentWeblUrl.EndWith('/') ? parentWebUrl + displayFormUrl + itemIdQuery : 
                                           parentWebUrl + "/" + displayFormUrl + itemIdQuery
0

Just shut down my VM and hence can't test but how about using something like SPContext.Current.Web.Url in combination with SPList.DefaultDisplayFormUrl. Note that SPWeb.Url gets the absolute URL for the website.

1
  • Seeing that the site collection is over at /sites/secondsite and DefaultDisplayFormUrl also contains that string in its returned url I don't think that's the way to go Commented Feb 7, 2014 at 8:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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