ClientContext.Current is null in Silverlight?

Posted on 12/13/2009 @ 4:50 PM in #SharePoint by | Feedback | 1966 views

Sooner or later, when building Silverlight apps that talk to SharePoint 2010 Client Object Model, you will run into this problem. You’ll try and access ClientContext.Current, and for some mysterious reason, it will be null!

Well, mystery solved. What you need to do is, you need to pass the current SharePoint site URL to the Client Object Model as an InitParam. In short, in your Silverlight Object Tag, add the following:

 

   1: "<param name=\"initParams\" value=\"MS.SP.url=" + SPContext.Current.Site.Url + "\" />"

(The above is shown as code-behind code, because that is where you’d have to add that).

By doing so, the Client Object model can now get access to ClientContext.Current.

Happy SharePointing! w00t!

Sound off but keep it civil:

Older comments..


On 3/8/2010 7:12:07 AM Fabian said ..
I am using HTML Form Web Part but dont can use dinamic url. If i pass a hard code url it work, if i pass SPContext.Current.Site.Url it doesnt work.

Sample:


<param name="InitParams" value="Windows=Main, MS.SP.url=http://mysite, WindowsHeight=220/> - work fine


<param name="InitParams" value="Windows=Main, MS.SP.url=" + SPContext.Current.Site.Url + ", WindowsHeight=220/> - dont work


On 8/24/2010 5:29:14 AM Sandeep said ..
Another way - http://snahta.blogspot.com/2010/08/current-web-url-in-silverlight.html

This will make it easier to use OOTB Silverlight WP to load the new XAP.


On 9/8/2010 9:14:18 AM Marcus said ..
Listen, I LOVE YOU. Thanks man, I got your book and I'll attend one of your classes, and when I do I'll make sure to shake your hand. It seems whenever I have a SharePoint/SL problem, you turn out to be the resolver. This one was really icing on the cake.


On 9/8/2010 9:59:24 AM Sahil Malik said ..
Marcus, I so wish u were a cute chick!


On 11/15/2011 8:50:04 AM asdf said ..
It Still is null....


I have no idea what to do man this is freaking me out


On 2/24/2012 12:35:24 PM Venky said ..
I have tried passing MS.SP.url=http://mysite/ in sandboxed visual webpart


and make sure it is rendering correct parameter like below


<param name='initParams' value='MS.SP.url=http://servername//'/>;

as well tried with out of the box Silverlight webpart

but in both options context is not working.

Please help me here.

Thanks in Advance


On 11/4/2012 2:02:44 PM Kalyan said ..
I am also facing exact problem Fabian.


Someone please show some light here.


Wheneve I try to use "<param name=\"initParams\" value=\"MS.SP.url=" + SPContext.Current.Site.Url + "\" />" I m getting "System.NullReferenceException: Object reference not set to an instance of an object."

I am loading my XAP thru content editor webpart and also added this parameter in the same webpart.

Please help