Apr 2, 2010

How to access the silverlight method through javascript

Fisrt time I am writing anything about Silverlight part .
Here scenario is that we need to access a control inside silverlight application and then need to execute some operation on that control through javascript which is written outside the silverlight application ,now consider it inside the hosting .aspx page.
Since directly we cannot access the silverlight control in the javascript as on rendering of page ,silverlight control does not come in the viewsource of the page. So the approach to expose the control is to access the public method inside silverlight application and then perform the required operation.
To achieve this functionality we are following the below approach
  • In the Loaded event or the constructor of the page we have to make call to the ( RegisterScriptableObject) method. It accepts two parameters:
    • A name, which  is used to  make calls to the application.
    • An object, which will be called.
Code snippet which is required to be added in the loaded event of the

HtmlPage.RegisterScriptableObject("page", this);

Note: Here ‘this’ is the page object.
We can call only public methods in Silverlight application from javascript . If we  want a method to be accessed from JavaScript, you have to add the ‘ScriptableMember’ attribute before the method declaration. Code Snippet which is to be added inside the xaml.cs of the control :

    [ScriptableMember]
        public void Start()
        {
// Do Something
        }


Now to access this public method from javascript .write this javascript method inside the .aspx page or the place from where you want to call the javascript.

<script type="text/javascript" language="javascript">
       function CallSilverLight() {
           var slControl = document.getElementById("_slControl");
           slControl.Content.page.Start();
         
       }
   </script>

1)       Here id is the control ID of Silverlight control .
2)       In this statement slControl.Content.page.Start();
‘page’ is the name which we have given while registering the Scriptable control in the loaded event of the page
HtmlPage.RegisterScriptableObject("page", this);

3)       ‘Start’ is the name of the public method which is used to select the tab on click of breadcrumb menu which is inside sharepoint
And finally call this javascript from any control or  on page load as per the requirement.

Initially this seems to be bit tricky ,but this is very usefull approach for interaction between Silverlight and .aspx page.
Please write to me if you face any problem while implementing it or if there is any other better approach.

Happy Coding J

No comments:

Post a Comment