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.)
January 19th, 2008 at 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?
January 20th, 2008 at 3:18 am
what’s the meaning of function invokeManagedCode(){
January 20th, 2008 at 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.
February 2nd, 2008 at 5:19 pm
Very very good tips…thanks
February 3rd, 2008 at 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.
February 3rd, 2008 at 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?
February 4th, 2008 at 12:12 pm
[...] Silverlight Tips/Tricks: Communicating between Javascript and C# [...]
April 6th, 2008 at 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..
December 2nd, 2008 at 12:49 am
I have been having some issues with Firefox 3. Silverlight will load and run ok but when I click a link that executes javascript code that calls a scriptible method, I get a javascript error that states that the “Control.Content” is undifined.
Everything works fine on IE, Safari, and even Chrome. The problem in firefox seems to be intermitant. It will work sometimes but fail other times. I may reload the browser then it will work. Sometimes it will not work no matter how many times I reload Firefox.
Feels like a race condition in Firefox.
You can see the issue at the following URL:
http://www.myonlineband.com/TopMusic.aspx
April 17th, 2009 at 6:51 am
hey there…
I’ve also experience that.
How can i fix this?