What you want to see on DotNetFunda.com ?
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 12845 |  Welcome, Guest!   Register  Login
Home > Articles > Silverlight > Invoke Javascript Methods from Silverlight Applications

Invoke Javascript Methods from Silverlight Applications

Article posted by Niladri.Biswas on 4/16/2012 | Views: 2681 | Category: Silverlight | Level: Beginner | Points: 250 red flag


In this tutorial, we will see how to invoke Javascript function through Silverlight applications

Download


 Download source code for Invoke Javascript Methods from Silverlight Applications


Introduction

In this article, I will show how to invoke Javascript methods from Silverlight. 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

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 "SilverlightApplication1" and the other for is WebApplication by "SilverlightApplication1.Web".

Step 2:

We will now design our Silverlight page.So open MainPage.xaml and write the below xaml code

<UserControl x:Class="SilverlightApplication1.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="400" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">

<Grid x:Name="LayoutRoot" Background="White">
<sdk:Label Height="28" HorizontalAlignment="Left" Margin="18,27,0,0" Name="label1" VerticalAlignment="Top" Width="120" Content="Enter First Value" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="144,27,0,0" Name="txtVal1" VerticalAlignment="Top" Width="216" />
<sdk:Label Content="Enter Second Value" Height="28" HorizontalAlignment="Left" Margin="18,61,0,0" Name="label2" VerticalAlignment="Top" Width="120" />
<TextBox Height="23" HorizontalAlignment="Left" Margin="144,61,0,0" Name="txtVal2" VerticalAlignment="Top" Width="216" />
<sdk:Label Content="Result" Height="28" HorizontalAlignment="Left" Margin="18,109,0,0" Name="label3" VerticalAlignment="Top" Width="120" />
<TextBlock Height="23" HorizontalAlignment="Left" Margin="144,109,0,0" Name="txtResult" Text="" VerticalAlignment="Top" Width="216" />
<Button Content="Add" Height="23" HorizontalAlignment="Left" Margin="20,165,0,0" Name="btnAdd" VerticalAlignment="Top" Width="75" Click="btnClick" />
<Button Content="Subtract" Height="23" HorizontalAlignment="Left" Margin="109,165,0,0" Name="btnSub" VerticalAlignment="Top" Width="75" Click="btnClick"/>
<Button Content="Multiply" Height="23" HorizontalAlignment="Left" Margin="206,165,0,0" Name="btnMul" VerticalAlignment="Top" Width="75" Click="btnClick" />
<Button Content="Divide" Height="23" HorizontalAlignment="Left" Margin="301,165,0,0" Name="btnDiv" VerticalAlignment="Top" Width="75" Click="btnClick"/>
</Grid>
</UserControl>

So our design will look as under

N.B.~As can be figure out that we have a common event handler for all the button controls which is btnClick

Step 3:

Next write the below code piece in the btnClick event

private void btnClick(object sender, RoutedEventArgs e)
{
var btnName = (sender as Button).Content;
switch (btnName.ToString())
{
case "Add":InvokeJS((object)new object[]{ (object)txtVal1.Text, (object)txtVal2.Text,(object)"+" });
break;
case "Subtract": InvokeJS((object)new object[] { (object)txtVal1.Text, (object)txtVal2.Text, (object)"-" });
break;
case "Multiply": InvokeJS((object)new object[] { (object)txtVal1.Text, (object)txtVal2.Text, (object)"*" });
break;
case "Divide": InvokeJS((object)new object[] { (object)txtVal1.Text, (object)txtVal2.Text, (object)"/" });
break;
}

}

The InvokeJS function is as under

void InvokeJS(params object[] items)
{
object result = System.Windows.Browser.HtmlPage.Window.Invoke("DoOperation", items);
txtResult.Text = result.ToString();
}

The HtmlPage.Window.Invoke method invokes a method on the current scriptable object(here Javascript) and optionally passes in one or more method parameters.

So in this case DoOperation is the javascript function name and we are passing an object array comprising of three elements viz. First Number, Second Number and the Operator

Step 4:

Open the SilverlightApplication1TestPage.aspx and implement the DoOperation javascript function

//Invoke this function from silverlight
function DoOperation(params)
{
var result = 0;
switch (params[2]) //params[2] is the operator(s) i.e. +,-,*,/
{
case '+': result = parseInt(params[0]) + parseInt(params[1]); break;
case '-': result = params[0] - params[1]; break;
case '*': result = params[0] * params[1]; break;
case '/': result = params[0] / params[1]; break;
default: alert("No such operation available");
}
return result;
}

Step 5:

So now we are all set.Build the solution.Make the SilverlightApplication1 as the startup project.Run the application

The below is the output for Addition operation

Conclusion

So we have learn as how to invoke Javascript function from Silverlight.Hope this article will be helpful as a reference.

Zip file is attached

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:6 year(s)
Home page:http://www.dotnetfunda.com
Member since:Monday, October 25, 2010
Level:Diamond
Status: [Member]
Biography:Lead Engineer at HCL Technologies Ltd., having 6 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: Pavan_Kumar | Posted on: 23 May 2012 09:04:04 AM | Points: 25

Nice article !!

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

In the first part of this series I outlined the basic information that you will need to know to get started with MVVM. In this part of the serials I will demonstrate to you how to create a Visual studio structure of MVVM without using any toolkit to help you. After the Structure is in place we will create our model.

In this article, we are going to learn about DataGrid in silverlight and its related properties.

In this article, we are going to have a fresh look at "what is Silverlight,how to install it,How will I know if Silverlight runtime is installed on my machine,what is XAML".

Welcome again to Dotnetfunda. Weeks ago one of our members here at Dotnetfunda asked a question on how to do a drag and drop and there was no answer on his question, so we realized that this type of a question will still come in the future. In this article I will give you a small hello world like demo on how to do a drag and drop in Silverlight.

In this article, we are going to learn how to work with Networking in SilverLight.

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. | 5/25/2013 6:43:19 AM