Subscribe to Subscribers
Talk to Webmaster Tony John


Tutorials » Silverlight tutorials »

How to call Javascript functions from Silverlight code ?


This Silverlight shows sample how to call Javascript functions from Silverlight controls code behind file


One of the advantages of Silverlight is, it has access to the Html document of the web page in which it is hosted. This enables Silverlight to access HTML elements in the page and also call Javascript methods.

The following steps shows how to call a Javascript method from Silverlight.

Open the ASP.NET or HTML page which hosts the Silverlight control. Add the Javascript method as shown below:


<script language="javascript"≫
function SayHello()
{
alert("Hello from JavaScript, invoked by Silverlight");
}
</script>


Now, open your XAML control file and add a button control as shown below:


<Grid x:Name="LayoutRoot" Background="White">
<Button x:Name="btnSayHello" Content="Say Hello"
Click="btnSayHello_Click"></Button>
</Grid>


Go to the code behind file for the XAML Page and add the event handler for the button click event:

private void btnSayHello_Click(object sender, RoutedEventArgs e)
{
HtmlPage.Window.Invoke("SayHello");
}


In order to use the HtmlPage class, you need to include the System.Windows.Browser

using System.Windows.Browser;

You are done. Run your Silverlight application and see. When you click on the button in the Silverlight control, you can see the popup message from the Javascript function.


You can download a sample project for this tutorial.




Next Chapter: How to show a popup layer within a Silverlight web page?
Previous Chapter: Create WCF service to retrieve session data - part II
More Chapters: Silverlight Tutorials
More Tutorials: Tutorial Index




Follow us on Twitter: https://twitter.com/dotnetspider

Active Members
TodayLast 7 Daysmore...

Awards & Gifts
Copyright © SpiderWorks Technologies Pvt Ltd., Kochi, India
2005 - 2012 All Rights Reserved.
.NET and other trademarks mentioned in this site belong to Microsoft and other respective trademark owners.
Articles, tutorials and all other content offered here is for educational purpose only.
We are not associated with Microsoft or its partners.