7

When working with server side code we can use the following line to obtain the url of the current web site:

var url = SPContext.Current.Web.Url;

How can we do the same when working with the client object model?

6

UPDATE: Shankar's comment is correct, my post does not really answer the original question. I must have misread it at the time. I leave my post for completeness but the other answers are the correct ones.


The Client Object Model (CSOM) equivalent to the SPContext is the ClientContext. However since CSOM is a remote API there is no current context (unless you are working with client-side code), you need to tell SharePoint the context by supplying the Site URL.

var siteUrl = "http://sp2013found/sites/demo";
using (var context = new ClientContext(siteUrl))
{
    var web = context.Web;
    context.Load(web);
    context.ExecuteQuery();
    ResultsListBox.Items.Add(web.Title);
}

When working with client-side code there is a current context because the code is running in a page that was generated by SharePoint.

var context = SP.ClientContext.get_current();
var web = context.get_web();
context.load(web);
context.executeQueryAsync(success, fail);

function success() {
    var message = jQuery("#message");
    message.text(web.get_title());
}

function fail(sender, args) {
    alert("Call failed. Error: " +
        args.get_message());
}
  • this answer completely misses the question. ClientContext code shown above does not show how to get the Url. I have tried, web.Url property is not initialized after doing context.Load(web); context.ExecuteQuery(); web.Title is one of the very few properties initialized and available. vote -1. – Shankar Apr 18 '14 at 16:43
5

If you're using client side code within a site, you can pull the URL real fast using

_spPageContextInfo.webAbsoluteUrl

  • 1
    Only once the page is loaded. Inside JSLink, this will not work. – trgraglia Feb 14 '17 at 8:38
2

You can't. That is server object model code. The object you should look at is ClientContext.

Even if you could use SPContext in Client Object Model code it would be null, so why bother?

0

In CSOM C# you can use

var url = clientContext.Web.Url;
  • for you downvoters - Ive found this answer works, but you need to load the Web first with clientContext.Load(clientContext.Web) followed by a clientContext.ExecuteQuery() – Taterhead May 30 '17 at 15:20

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.