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?
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());
}
If you're using client side code within a site, you can pull the URL real fast using
_spPageContextInfo.webAbsoluteUrl
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?
In CSOM C# you can use
var url = clientContext.Web.Url;
clientContext.Load(clientContext.Web)
followed by a clientContext.ExecuteQuery()
Commented
May 30, 2017 at 15:20