Communicating between Silverlight and ASP.NET via JavaScript

You love Silverlight, you love ASP.NET. You want Silverlight and ASP.NET to love each other. Enter the third party in the technology love triangle, JavaScript.

In my scenario, I had an ASP.NET page that opened another page that hosted a Silverlight control. When the user selected some data and clicked the Save button, the Silverlight window should pass that data to the original ASP.NET page, as well as close the opened window.

So in the opening page, I use some JavaScript to open a new window:'SilverlightPage.aspx', 'MyWindow');

After I’ve done wonderful things in Silverlight, I click my Save button:

<Button x:Name="SaveProperty" Content="Save" Click="SaveProperty_Click"  />

Which calls it’s code-behind function. Here is the magic, the HtmlPage.Window.Invoke function. In my code, I use it to call a JavaScript function defined in SilverlightPage.aspx, passing in the values from two TextBox controls in Silverlight.

 private void SaveProperty_Click(object sender, RoutedEventArgs e)
 HtmlPage.Window.Invoke("PopulateOneTwo ", TextBox1.Text, TextBox2.Text);

All the PopulateOneTwo function does is pass on the variables from Silverlight to the calling page, then close itself. Remember, PopulateOneTwo  is defined in SilverlightPage.aspx, the page that holds the Silverlight control.

function PopulateOneTwo(varOne, varTwo) {
window.opener.PopulateValues(varOne, varTwo);

Back to the original ASP.NET page, I have the PopulateValues function to actually take the values passed from the SilverlightPage.aspx (and the Silverlight code) and populate the TextBox controls:

function PopulateValues(varFirst,varSecond) 
     var One= document.getElementById("txtOne");
     var Two= document.getElementById("txtTwo");
     One.value = varFirst; 
     Two.value = varSecond;

<asp:TextBox ID="txtOne" runat="server"/> 
<asp:TextBox ID="txtTwo" runat="server"/>

Bada bing, done, and I have the values passed into an ASP.NET from Silverlight.

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: