Random geekery since 2005.

Husband, father, programmer, speaker, writer, blogger, podcaster, collector, traveler, golfer.

TUTORIAL #5: Calling Javascript From Silverlight 2

Written in


In this post, I want to show you how incredibly simple it is to call a Javascript function from the managed code of your Silverlight application. We’ll also be able to retrieve a value from that function, and return it to Silverlight. If you’re just hunting for the syntax, just jump to step #6. This post covers creating everything from scratch, in both VB and C#.

1) Create your Silverlight project and sister web site.

I’ve already documented creating a new Silverlight project here, so I’ll let you read that one first, if necessary.

2) Let’s write a “legacy” Javascript function.

We need a JS function to call, so let’s make it interesting. Let’s say that I have some code from a previous app that determines all of the prime numbers from 1 to 500. I don’t necessarily want to rewrite that, so let’s just reuse it. Here’s the code:

//The purpose of this code is to find all of the prime numbers under 500.
//The definition of a prime number is one that is only divisible by 1 and itself.
//We are utilizing the Sieve of Eratosthenes to enhance our algorithm.
var primeArray = new Array();
var primecounter = -1;
var primeFlag = true;

function getPrimes(useri){
     primeArray.length = 0;
     primecounter = -1;
     var i = 500;
     if (useri != “”){
          i = useri;
     for (j=1;j<=i;j++) checkForPrime(j);
          return primeArray.join(” “);
function integerCheck(newvalue){
     var regexp = /(^dd*$)/;
     if(regexp.exec(newvalue)) primeFlag = false;
function checkForPrime(j){
     primeFlag = true;
     for (k=0;k<=primecounter;k++){
          if ((primeArray[k] != “”)&&(primeFlag)){
               if ((j/primeArray[k] != 1)&&(j/primeArray[k] != j)){
     if (primeFlag){
          primeArray[primecounter+1] = j;

3) Add that JS code to our web page.

Just add a <script> block in the <head> of your web page, and put the above code inside. Done!

4) Now we need to write some XAML.

Open your Page.xaml file that was created for you, and let’s add a button. We’ll use this button’s event handlers to call our Javascript function eventually. To add a button, here’s the XAML I am using inside of the &ltGrid> I was provided:

<Button Width=”100″ Height=”50″ Content=”Get Primes!” />

5) Add an event handler to our button.

In our button, add the “Click” property, and Intellisense will prompt you to create a “New Event Handler.” This will create the method in the code behind file for you. Here’s the new button XAML:

<Button Width=”100″ Height=”50″ Content=”Get Primes!” Click=”Button_Click” />

6) Time to call that Javascript function.

Jump into the code behind file for your XAML (page.xaml.cs or page.xaml.vb by default). There’s a new method called Button_Click for you. We are going to write ONE line of code to make this happen. And here it is:





I kinda lied though on the 1 line of code thing. For C#, we also need the “using System.Windows.Browser;” statement. The “getPrimes” value we are passing is the name of the Javascript function we want to call. But this only gets us halfway there. My JS function creates a list of prime numbers and then sends them back as a return value. So we need to actually do something with this value.

7) Refactoring our code to use the return value.

So we know we can call a Javascript function, but returning the value is going to be a little more challenging. We need to capture the return value, cast it as a string (everything from Javascript is assumed to be an object), and display it in our Silverlight app. But let’s make it a little more interesting. Let’s also change things to pass parameters to our JS function as well.

First, we need some new XAML elements. I’ve added a <TextBlock> to my XAML page to display the primes, as well as a <TextBox> to gather the number of primes the user wants to generate. Here’s the new XAML code:

<StackPanel x:Name=”LayoutRoot” Background=”White”>
     <TextBlock Width=”400″ Text=”Primes to what number?” TextAlignment=”Center” />
     <TextBox Width=”100″ Height=”24″ x:Name=”primecount” Margin=”0,0,0,10″ />
     <Button Width=”100″ Height=”50″ Content=”Get Primes!” Click=”Button_Click” />
     <TextBlock x:Name=”primebox” Width=”800″ TextWrapping=”Wrap” />

And now here’s my new C# and VB code inside my Button_Click methods to pass our value and display this data:


string primeArray = (string) HtmlPage.Window.Invoke(“getPrimes”, primecount.Text);
primebox.Text = primeArray;


Dim primeArray = System.Windows.Browser.HtmlPage.Window.Invoke(“getPrimes”, primecount.Text)
primebox.Text = primeArray.ToString

What will happen in this scenario is that if the user provides a value, we will use it, and if they don’t, we’ll default to 500.

8) So let’s run it!

That’s it! We’ve successfully called a Javascript function from Silverlight (in both C# and VB), retrieved the value it created, and displayed it in our application. We also passed specific parameters to that Javascript function to influence its behavior. Click the Demo button to see it in action.

9) Source Code Links

I’ve provided the source code for this example in both C# and VB. Just click the appropriate button.

C#.NET Source Code VB.NET Source Code

kick it on DotNetKicks.com


4 responses to “TUTORIAL #5: Calling Javascript From Silverlight 2”

  1. Gilberto Avatar

    Love the tutorial, simple, strait to the point, and easy to understand. Thanks for posting this. Greate site by the way, Love the intergration of the silverlight on the page looks great.

  2. Dako Avatar

    Thank you very much, this helped for me. Because I wanted to put my Siverlight values on a ASPX page.

  3. Ruchita R. Kadam Avatar
    Ruchita R. Kadam

    Hello Jeff,
    This is a very helpful tutorial..
    But unfortunately the download link is not working ….I want to study this code so that I can add my js functions to my silver-light code!!
    Can you please upload another link or email me the sample code to my g mail account..?!

    Hope to get your reply..
    Please reply A.S.A.P.

    Thanks & Regards,

  4. srinivas Avatar

    Excellent info.

Leave a Reply

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

WordPress.com Logo

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

Facebook photo

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

Connecting to %s

Create a website or blog at WordPress.com

%d bloggers like this: