Share via


Exercise 2: Calling Silverlight code from JavaScript

This exercise walks you through the process of calling managed Silverlight code inside a custom Silverlight application from JavaScript on an HTML page.

Task 1 – Attaching an Event Handler

  1. In this task, you will write code in Silverlight to attach a managed code event handler to an HTML button declared in the HTML DOM. When the button is clicked, the managed code will execute.
  2. If it is still open, close the browser used in Exercise 1
  3. Using Visual Studio 2010, open the starter solution named CallSL from the <Install>\Labs\HTMLBridge\source\begin\Call Silverlight folder. Solution Explorer should look like this:

    Figure 6

    Solution explorer

  4. From Solution Explorer, open up the file SilverlightApplication1WebPartPage.aspx and scroll all the way to the bottom of the page. Examine the HTML within the two Call Silverlight Managed Code comments. It includes two HTML button controls:
    1. createPalindromeLink, which does not have an onclick handler
    2. checkPalindromeLink, which has an onclick handler configured to call a method named Call_SL.
  5. The first button is used in this exercise; the second button is for in Task 2.
  6. From Solution Explorer, open up the Silverlight code behind file by expanding the MainPage.xaml file and double-clicking on MainPage.xaml.cs.
  7. The starter solution includes some code already added within the Utility Methods code region:

    Figure 7

    Utility methods

  8. [Optional] Expand the Utility Methods code region and explore the code there.
  9. Position your cursor on line 12 and add the following using declaration and then hit <Enter>:

    C#

    using System.Windows.Browser;

    Referencing this namespace gives us shorthand access to the HTML Bridge classes (such as HtmlDocument, HtmlPage and HtmlElement) we will use throughout the rest of this exercise.

  10. Position your cursor on line 17, just below the class declaration and hit <Enter>. Type the following declarations and then hit <Enter>:

    C#

    HtmlDocument htmlDoc = HtmlPage.Document; HtmlElement htmlEl; HtmlElement htmlButton;

  11. This sets up the objects we will use to access the HTML DOM of the page hosting our Silverlight application.
  12. Position your cursor inside the MainPage constructor (line 24) and hit <Enter>. Enter the following code:

    C#

    htmlButton = htmlDoc.GetElementById("createPalindromeLink"); htmlButton.AttachEvent("onclick", new EventHandler(this.OnCreatePalindromeClicked));

    This code connects to the HTML button with the ID of createPalindromeLink and attaches the managed code event handler OnCreatePalindromeClicked to its onclick event.

  13. Position your cursor after the closing curly brace on line 29 and hit <Enter> twice.
  14. Type the following code:

    C#

    void OnCreatePalindromeClicked(object sender, EventArgs e) { htmlEl = htmlDoc.GetElementById("UserText"); htmlEl.SetAttribute("value", GetPalindrome()); }

    This code is called when the Create Palindrome button is clicked in the browser. It first connects to the HTML textbox with an ID of UserText. It then sets the value of the textbox to the value returned from the GetPalindrome utility method.

  15. This completes the coding for this Task. We will test this at the end of Task 2.

Task 2 – Using a ScriptableType

In this task, you will write managed code in Silverlight as well as JavaScript code in the ASPX page to call a Silverlight method directly from JavaScript.

  1. If it is still open, close the browser used in Task 1.
  2. Back in Visual Studio, open the MainPage.xaml.cs file and place your cursor at the end of line 27 – the last line in the MainPage constructor and hit <Enter>
  3. Type the following code:

    C#

    HtmlPage.RegisterScriptableObject("SL", this);

  4. This code registers the current Silverlight object (MainPage) for scriptable access from JavaScript under the name SL. This step opens a channel into the managed code that can be called from JavaScript.
  5. Position your cursor just above the CheckPalindrome method (on line 59 in the Utility Methods code region) and type the following code:

    C#

    [ScriptableMember]

  6. This attribute causes the member it decorates to be available for JavaScript calls through the channel opened in the previous step.
  7. From Solution Explorer, open up the file SilverlightApplication1WebPartPage.aspx and scroll all the way to the bottom of the page. Recall from Task 1 that there were two HTML buttons defined on this page. We used the first button in Task 1. We’ll wire up the second button now.
  8. Place your cursor between the last and the HTML comment and type the following code:

    JavaScript

    <script type="text/javascript"> function Call_SL() { var SLId = "g_c24198d9_d504_4132_b56c_585e456d8855"; var SLPlugin = document.getElementById(@"SilverlightObjectTag_WebPartctl00 _m_" + SLId); var userText = document.getElementById("UserText").value; var retVal = SLPlugin.Content.SL.CheckPalindrome(userText); if (retVal == "true") { alert(userText + " IS a palindrome"); } else { alert(userText + " is NOT a palindrome"); } } </script>

  9. This JavaScript code connects to the Silverlight plugin object in the browser and calls into the managed code method CheckPalindrome passing in the string from the HTML textbox. It then displays the appropriate message depending on the value returned from Silverlight.
  10. This completes the coding, so hit F5 to test out the solution. After Visual Studio launches the browser, navigate to https://intranet.contoso.com/sites/htmlbridge/SitePages/SilverlightApplication1WebPartPage.aspx.
  11. Click the Get Palindrome button to fill the HTML textbox with a random palindrome generated in the Silverlight managed code.
  12. Click the Check Palindrome button to verify whether the text in the HTML textbox is in fact a palindrome. This code calls the CheckPalindrome method in the managed code, exposed through the channel opened in step 4 and the attribute added in step 5. Your page should something like look like this:

    Figure 8

    Message dialog

Exercise 2 Verification

In order to verify that you have correctly performed all steps of exercise 2, proceed as follows:

Verification 1

In this verification, you can compare the anticipated output shown in step 9 with the actual output shown on your screen. If your screen shows a similar view (the actual string in the textbox and the alert text may differ), you have completed the exercise successfully.