Invoke Silverlight Methods through Javascript

Niladri.Biswas
Posted by in Silverlight category on for Beginner level | Points: 250 | Views : 6261 red flag
Rating: 4 out of 5  
 1 vote(s)

In this article we will look as how to invoke Silver light methods from javascript


 Download source code for Invoke Silverlight Methods through Javascript

Invoke Silverlight Methods through Javascript

Introduction

In this article, I will show how to invoke Silverlight methods from javascript. We will learn this by performing a simple calculator example with some basic arithmetical functionalities being expose.

What we need to perform the experiment?

Well for doing this experiment, what we need is the following

  1. VS 2010
  2. Asp.net
  3. Silverlight
  4. System.Web.Silverlight.dll(If your system does not have this, you can download from here or any where else if you found a link)

N.B.System.Web.Silverlight.dll in not part of the SDK since Silverlight 3

What is the importance of System.Web.Silverlight.dll?

It provides the ASP.NET Silverlight server control that was designed to make it easier to create the object tag needed to describe the silverlight plug-in.Since this server-side control was removed since Silverlight SDK 3,so we have to build the object tag by ourself.

Steps to perform the experiment

Step 1:

Open the VS2010 and File->New->Project->Silverlight(Choose from installed templates) and choose Silverlight Applications.Give a proper name to the Application and click on OK button

In the next screen "New Silverlight Application" that appears, keep everything as it is and click on the OK button

Two projects will be created in the solution explorer - one for Silverlight by the name "SL_JS_Experiment" and the other for is WebApplication by "SL_JS_Experiment.Web".

Step 2:

Next, add a reference to System.Web.Silverlight.dll to the web project which is "SL_JS_Experiment.Web" here

Step 3:

We will now add the basic maths function (Add, Subtract,Multiply, Divide) in the Silverlight code behind which is "MainPage.xaml.cs" file.

First we need to add System.Windows.Browser.HtmlPage.RegisterScriptableObject(string scriptKey, object instance) in the Silverlight page constructor

.
public MainPage()
{
InitializeComponent();
System.Windows.Browser.HtmlPage.RegisterScriptableObject("SilverlightMethods", this);
}

The RegisterScriptableObject method registers a managed object for scriptable access by JavaScript code.

Step 4:

Once done, next for every function that we will write, we need to decorate that with the [ScriptableMember] attribute.This attribute indicates that a specific property, method, or event is accessible to JavaScript callers.It resides in System.Windows.Browser namespace.

[ScriptableMember]
public int Addition(int first, int second)
{
return (first + second);
}

[ScriptableMember]
public int Subtraction(int first, int second)
{
return (first - second);
}

[ScriptableMember]
public int Multiplication(int first, int second)
{
return (first * second);
}

[ScriptableMember]
public int Division(int first, int second)
{
return (first / second);
}

The complete code is as under

using System.Windows.Browser;
using System.Windows.Controls;

namespace SL_JS_Experiment
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
System.Windows.Browser.HtmlPage.RegisterScriptableObject("SilverlightMethods", this);
}

[ScriptableMember]
public int Addition(int first, int second)
{
return (first + second);
}

[ScriptableMember]
public int Subtraction(int first, int second)
{
return (first - second);
}

[ScriptableMember]
public int Multiplication(int first, int second)
{
return (first * second);
}

[ScriptableMember]
public int Division(int first, int second)
{
return (first / second);
}
}
}

Step 5:

Now add new aspx page in the web-application project(SL_JS_Experiment.Web) and call it as "Test.aspx"

Step 6:

We need to register the "System.Web.Silverlight.dll" assembly in our web page.Henceforth, let us add the below line of code on top of the aspx page

<%@ Register Assembly="System.Web.Silverlight" Namespace="System.Web.UI.SilverlightControls" TagPrefix="asp" %>

Step 7:

Now let us complete the design.Write the below code inside the body tag

    <form id="form1" runat="server">
<asp:ScriptManager ID="scriptManager" runat="server" />
<asp:Silverlight Height="100px" ID="slCtrl" runat="server" Source="~/ClientBin/SL_JS_Experiment.xap"
Width="100px">
</asp:Silverlight>
<table>

<!-- For Input -->
<tr>
<td>
Enter First Value: <input id="textValue1" type="text" />
</td>
<td>

</td>
<td>
Enter Second Value: <input id="textValue2" type="text" />
</td>
<td>
=
</td>
<td>
<input id="textResult" type="text" readonly="readonly" />
</td>
</tr>

<!-- For Operations -->
<tr>
<td>
<input id="btnAdd" type="button" value="Add" onclick="javascript:CallSLFunction('+');" />
<input id="btnSubtract" type="button" value="Subtract" onclick="javascript:CallSLFunction('-');" />
<input id="btnMultiply" type="button" value="Multiply" onclick="javascript:CallSLFunction('*');" />
<input id="btnDivide" type="button" value="Divide" onclick="javascript:CallSLFunction('/');" />
</td>
</tr>
</table>
</form>

The "SL_JS_Experiment.xap" file is found in the ClientBin folder

N.B.~A detail about xap file can be found from here

The code is pretty simple to understand. We have two input textbox controls where we will provide teh input values and a result textbox(which is readonly) where the output will be presented.

Also we have 4 buttons that are invoking the "CallSLFunction" function that accepts one argument as operator.

The design view looks as under

Step 8:

Now we will implement the "CallSLFunction" javascript function that is as under

function CallSLFunction(operator) 
{
//variable that stores reference of the asp:Silverlight control
var slCtrl = document.getElementById('slCtrl');

//variable that will store the result
var result = 0;

if (null != slCtrl) {

var firstInputValue = document.getElementById('textValue1').value;
var secondInputValue = document.getElementById('textValue2').value;

switch (operator) {
case '+':
result = slCtrl.Content.SilverlightMethods.Addition(firstInputValue, secondInputValue);
break;
case '-':
result = slCtrl.Content.SilverlightMethods.Subtraction(firstInputValue, secondInputValue);
break;
case '*':
result = slCtrl.Content.SilverlightMethods.Multiplication(firstInputValue, secondInputValue);
break;
case '/':
result = slCtrl.Content.SilverlightMethods.Division(firstInputValue, secondInputValue);
break;
default:
alert("So such operation available");
}

//display the result
document.getElementById('textResult').value = result
}
}

Again, it is a simple code where we are invoking the silverlight function based on the operator being passed as argument.

But the point of interest is how we are invoking the Silverlight function!Well, are are doing so by calling "ScriptKey" of the RegisterScriptableObject function of Silverlight

Step 9:

So now we are all set.Build the solution.Make the web project (SL_JS_Experiment.Web) as the startup project and "Test.aspx" as start page. Run the application

The below is the output for Addition operation

Conclusion

So we have learnt as how to invoke silverlight function from javascript.Hope this article will be helpful as a reference.

Zip file is attached

Page copy protected against web site content infringement by Copyscape

About the Author

Niladri.Biswas
Full Name: Niladri Biswas
Member Level: Platinum
Member Status: Member
Member Since: 10/25/2010 11:04:24 AM
Country: India
Best Regards, Niladri Biswas
http://www.dotnetfunda.com
Technical Lead at HCL Technologies

Login to vote for this post.

Comments or Responses

Posted by: Ashoknalam on: 5/29/2012 | Points: 25
Nice

Login to post response

Comment using Facebook(Author doesn't get notification)