Congratulations to all monthly winners of May 2013 !!! They have won INR 2900 cash and INR 27497 worth prize.
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 10897 |  Welcome, Guest!   Register  Login
Home > Articles > Silverlight > Invoke Silverlight Methods through Javascript

Invoke Silverlight Methods through Javascript

1 vote(s)
Rating: 4 out of 5
Article posted by Niladri.Biswas on 4/15/2012 | Views: 2447 | Category: Silverlight | Level: Beginner | Points: 250 red flag

Advertisements

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

Download


 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

Advertisements

If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:



Please Sign In to vote for this post.

Experience:7 year(s)
Home page:http://www.dotnetfunda.com
Member since:Monday, October 25, 2010
Level:Diamond
Status: [Member]
Biography:Technical Lead at HCL Technologies Ltd., having 7 years of experience in IT field.
I love to explore new technologies and love challenges and try to help others as much as possible not only by coding but also by all possible means.
 Responses
Posted by: Ashoknalam | Posted on: 29 May 2012 12:41:21 PM | Points: 25

Nice

>> Write Response - Respond to this post and get points
Related Posts

This article will talk about three ways of binding object properties with SilverLight user interfaces.  We will first go through the fundamentals of the 3 bindings and then take up a small sample which will demonstrate how the binding works. We have also attached the source for the same.

It has been a while since I have written an article. This is because of the load of work that I am doing at my job, privately and here in DNF. Since well I have free time, I will dedicate this time to write new and finish the series that I have started and never finished. This is a small article that i use to demonstrate to you how to play a video in Silverlight.

In this Article we are going to learn Silverlight controls like Grid and TextBlock and related properties.

A friend of mine, who is doing working on a GIS project, asked me, if I could get him a cool control that will show maps based on the Coordinates at ease without worrying about other map problems that GIS developers come across every day. So this triggered me to write something nice with the Map control from Telerik.

In this article, we will look into some of the aspects of Silverlight Datagrid as a) Create a custom entity and bind to DataGrid through code using AutoGenerated Column On b) DataGrid binding by manually defining columns using Column Collection c) Paging in DataGrid using DataPager and PagedCollectionView class d) Displaying images in DataGrid

More ...
About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you find plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 6/19/2013 3:41:33 PM