Communicating between ASP.NET and Silverlight using JavaScript

Tuesday, January 26 2010


Getting more and more people asking about communication between Silverlight and ASP.NET UIs, when you have different controls created in ASP.NET and you don’t want to redo them in Silverlight, yet you are using a Silverlight control on your ASPX page, how do they communicate between those 2 tiers?

Given that Silverlight is client side, you’ll have to use JavaScript in ASP.NET to accomplish just that. Being able to avoid postbacks and communicate calling each others javascript application for the UI. If you want to call any server side code, you can just use WCF RIA Services or a simple webservice.

The steps to do the communication are in Silverlight you need to register the class to expose it to JavaScript.

public partial class MainPage : UserControl
   {
       public MainPage()
       {
           InitializeComponent();

           // Register Silverlight to be exposed in JavaScript
           HtmlPage.RegisterScriptableObject("ScriptablePageObject", this);
       }

 

Any method that can be called needs to add the ScriptableMember attribute.

[ScriptableMember]
       public void JSButtonClick(string sText)
       {
           MyText.Text = sText;
       }

Now in JavaScript you can call the method JSButtonClick:

function callSilverlight() {           

        var text1 = document.getElementById("TextBox1");
        document.getElementById('Xaml1').Content.ScriptablePageObject.JSButtonClick(text1.value);
    }

<input ID="Button1" type="button" OnClick="javascript:callSilverlight()" value="Send text to Silverlight" />

The way around, calling JavaScript from inside Silverlight just using the Invoke method found at HtmlPage.Window. First parameter will be the method.

private void Button_Click(object sender, RoutedEventArgs e)
        {
            HtmlPage.Window.Invoke("myJSFunction", MyTextBox.Text);
        }

In JavaScript the method will look like this:

function myJSFunction(mytext) {
            var text1 = document.getElementById("TextBox1");
            text1.value = mytext;
        }

 

For a easier way to read the code I use CodePaste.Net where you’ll find the full code:

Full code for the Default.aspx code found here

Full code for the XAML code found here

Full code for the XAML.cs found here

 

Hope this helps

Cheers

Al