Calling Silverlight Method using JavaScript in

Hi Folks...
Today, I am going to explain the topic "Calling Silverlight Method from JavaScript ". Before you are doing this example, check your Visual Studio has System.Web.Silverlight dll references other wise you need to add this reference in your application references. click here to download the System.Web.Silverlight.dll. Now let's take each of these steps one by one.

Step 1:

First download the System.Web.Silverlight dll from above link, After that download the file and then Unzip the file and save the file in your local system

Step 2:

open the visual studio 2008/2010 and select new silverlight application and change the name as
SilverlightApplication and press OK.

Then in solution explorer it will create two projects one for silverlight name it as “SilverlightApplication” and another one is webapplication name it as “SilverlightApplication.Web”

Step 3:

Next, Right click on the Web Project in the solution explorer and click on the Add Reference.

Step 4:

Next, click on the browse button and select the System.Web.Silverlight.dll file from your computer and add that System.Web.Silverlight.dll file to your application.
Let's discuss the Silverlight code behind:

The first thing that we need to add the following code to our Silverlight page constructor. after that, add the [ScriptableMember] Property at the top of method, which is calling method from javascript.

Let's go to the silverlight code behind cs file(MainPage.Xaml.cs):
using System.Windows.Browser; //[ScriptableMember] is property namespace.

namespace SilverlightApplication
     public partial class MainPage : UserControl
      public MainPage()

      public float SumOfTwoNumbers(float firstVal, float secondVal)
          return ( firstVal + secondVal );

Now add new aspx page in your webapplication and give name as CallingSLmethodFromJS.aspx

Add this code block on top of the aspx page:
<%@ Register Assembly="System.Web.Silverlight" Namespace="System.Web.UI.SilverlightControls" TagPrefix="asp" %>

Add this script block in header part of aspx page.

In the above method, first I try to get the object of the Silverlight Control and then get the two textbox values. After that I called the Silverlight Code behind method with two parameters which I am getting from textbox values.

Add this code block in body tag:

Here SilverlightApplication.xap is compressed file while building the application it will be created.

Calling Silverlight Method from JavaScript

In the above code block, I took two Textboxs and Button on my page, the click event of button will call the JavaScript method, and this method will call the Silverlight method.

Finally, build the solution and check the output.

Thats it, I hope you like this article.


© 2012 Pioneers Code All Rights Reserved Pioneers Code