Silverlight Tips/Tricks: Communicating between Javascript and C#
This post is not an article. Just small notes that I made while I’m playing Silverlight. I attached all sample sourcecodes in this post. I hope you will find it useful. If you have some tips that you want to share with others, please let me know.
Contents
- Calling Javascript function from C#
- Passing the parameters to Javascript function from C#
- Calling C# function from Javascript
Tip #1. How to call Javascript function from C#
Download : Sourecode (CallJSFromCSharp.zip)
- Add System.Windows.Browser namespace
using System.Windows.Browser;
- Make your class scriptable by adding [Scriptable] attribute
[Scriptable] public partial class Page : Canvas { - Register the scriptable object in constructor of your class or Page_Load
WebApplication.Current.RegisterScriptableObject("EntryPoint", this); - Add eventhandler in your class
[Scriptable] public event EventHandler CallbackToBrowser;
- Open test.html.js file and Add onload() event in Silverlight.createObjectEx()
function createSilverlight() { Silverlight.createObjectEx({ source: "Page.xaml", parentElement: document.getElementById("SilverlightControlHost"), id: "SilverlightControl", properties: { width: "100%", height: "100%", version: "1.1", enableHtmlAccess: "true" }, events: { onLoad: OnLoaded } });// Give the keyboard focus to the Silverlight control by default document.body.onload = function() { var silverlightControl = document.getElementById('SilverlightControl'); if (silverlightControl) silverlightControl.focus(); } function OnLoaded(sender, args) { sender.Content.EntryPoint.CallbackToBrowser = onManagedCallback; }Note: “EntryPoint” is the scriptable object that you register in the PageLoad event in C#. And “onManagedCallback” is the name of Javascript function that you want to call from C#.
- Add the following function that you want to call from C# in TestPage.html.js
function onManagedCallback(sender, args) { alert("JS!"); } - You can call Javascript function from C# by raising CallbackToBrowser event
if (CallbackToBrowser != null) { CallbackToBrowser(this, new EventArgs()); }
Tip #2. How to pass the parameters to Javascript function from C#
The default EventArgs class doesn’t have the parameters so that we have to create our own class which is inherited from EventArgs. Don’t forget to make it scriptable. Otherwise, it won’t work. (Thanks to Shawn Wildermuth who pointed me my mistake in this thread.)
Download : Sourcecode (PassParasToJsFromCSharp.zip)
- Follow the step that I mentioned in Tip #1.
- Add your own eventargs class in your silverlight project
[Scriptable] public class EventArgs<T> : EventArgs { private T _data;public EventArgs(T args) { _data = args; } [Scriptable] public T Data { get { return _data; } } } - You have to change the code a lit bit for calling the javascript function from previous example
if (CallbackToBrowser != null) { CallbackToBrowser(this, new EventArgs<string>("my value")); } - then, you can get the value which is passed from C# in Javascript function.
function onManagedCallback(sender, args) { if(args.Data){ alert(args.Data); } }
Tip #3: Calling C# function from Javascript
Download : Sourcecode(CallCSharpFromJS.zip)
- Register the scriptable object in Page_load event of Page.xaml.cs.
WebApplication.Current.RegisterScriptableObject("EntryPoint", this); - Add one button in TestPage.html and call the javascript function on onclick event of that button
<input type="button" value="Click Me" onclick = "invokeManagedCode();" />
- Write the javascript function to invoke the C# function.
function invokeManagedCode(){ var control = document.getElementById("SilverlightControl"); control.Content.EntryPoint.Test(); }Note: “SilverlightControl” is the id of Silverlight object that you created in TestPage.html.js. (If you are Silverlight 1.1 developer, you might not notice about that. )
- Write the scriptable C# function like below
[Scriptable] public void Test() { } - Set the breakpoint and run the application. (C# function will be fired when you click the button.)

























Tejasvi Hegde said
am January 19 2008 @ 3:20 am
Good tips.
Have you tried calling JavaScript function directly from inside Managed code ? i.e. Calling alert() from inside C# without assigning callbacks?
JavaScript Onload said
am January 20 2008 @ 3:18 am
what’s the meaning of function invokeManagedCode(){
Michael Sync said
am January 20 2008 @ 3:48 am
I haven’t tried it yet.. I will let you know whether it’s possible to do that or not..
This is the name of Javascript that support to invoke the C# code. Please take a look at step 3 of Tip #3.
ihtesham said
am February 2 2008 @ 5:19 pm
Very very good tips…thanks
ihtesham said
am February 3 2008 @ 3:38 am
hi
The following code give me ‘unspecified error’
var cont = silverlightControl.content.entrypoint;
cont.CreateHeader(w,h);
where c# code is:
[Scriptable]
public void CreateHeader(string width, string height)
{
int w = int.Parse(width);
int h = int.Parse(height);
Can you please help me…i have spent hours on it to solve but unsuccessfull so far.
Michael Sync said
am February 3 2008 @ 5:56 am
>>var cont = silverlightControl.content.entrypoint;
I think this is incorrect. where do you put this code? Can you show me full code? What are you trying to do?
I didn’t write like that in my sample, isn’t it?
Wöchentliche Rundablage: ASP.NET, ASP.NET MVC, System.AddIn, Silverlight, LINQ, C# 3.0, WPF, XBAP… | Code-Inside Blog said
am February 4 2008 @ 12:12 pm
[...] Silverlight Tips/Tricks: Communicating between Javascript and C# [...]
Michael Sync said
am April 6 2008 @ 8:46 am
Please take a look this post Walkthrough: Calling Managed Code from Client Script if you are using Silverlight 2 beta1.
Hope it helps..