in Silverlight

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.)

Leave a Reply

  1. Good tips.
    Have you tried calling JavaScript function directly from inside Managed code ? i.e. Calling alert() from inside C# without assigning callbacks?

  2. Have you tried calling JavaScript function directly from inside Managed code ? i.e. Calling alert() from inside C# without assigning callbacks

    I haven’t tried it yet.. I will let you know whether it’s possible to do that or not..

    what’s the meaning of function invokeManagedCode(){

    This is the name of Javascript that support to invoke the C# code. Please take a look at step 3 of Tip #3.

  3. 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.

  4. >>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?

  5. 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

  6. Hello Michael,
    I am working on Silverlight 5.
    I want to integrate javascript with silverlight.
    The js functions or jquery must get embedded into my silverlight page,
    For eg. If there is a animated banner it must be seen in my silverlight page along with my other controls.
    The file which you have uploaded : CallJSFromCSharp.zip is not running.
    Please upload it again or help me the steps to do the above.
    Hope to get your reply soon..

    Thanks & Regards,
    Ruchita Kadam