DCSIMG
Call Silverlight from JavaScript - Gady Elkarif's Blog

Gady Elkarif's Blog

Call Silverlight from JavaScript

Call Silverlight from JavaScript

This post is about great feature - the Managed HTML Bridge.

With this feature, you can use JavaScript to call Scriptable managed code include properties, methods and events.

In the previous post I wrote about Creating Silverlight Controls and Web Service with ASP.NET Futures, I will use this type of project to create a Web Application, and Xaml control.

Register the Class as Scriptable Object 

After creating the Web Application and a Silverlight Project, lets register the class as scriptable object, inside the Page_Loaded method:

    [Scriptable]

    public partial class Page : Canvas

    {

        HtmlElement m_buttonElement = null;

 

        public void Page_Loaded(object o, EventArgs e)

        {

            // Required to initialize variables

            InitializeComponent();

 

            WebApplication.Current.RegisterScriptableObject("MyControl", this);

 

            m_buttonElement = HtmlPage.Document.GetElementByID("button1");

        }

 

        [Scriptable]

        public void Hello(String name)

        {

           // Access the HTML DOM from Managed Code

            m_buttonElement.SetAttribute("value", String.Format("Hello {0}!", name));

        }

    }

 

The Scriptable Attribute define the class and the method accessible from JavaScript

Calling Managed Code from JavaScript

The following html sample page describe how to call the managed code using JavaScript.

<head runat="server">

    <title>Untitled Page</title>

    <script type="text/javascript">

    function onClickButton()

    {

        var control = document.getElementById("Xaml1");

 

        control.content.MyControl.Hello("Gady");

 

        control.content.findName("tb").Text = "Hello Silverlight";

    }

    </script>     

</head>

<body>

    <form id="form1" runat="server">

        <asp:ScriptManager ID="ScriptManager1" runat="server" />

        <div>

            <asp:Xaml ID="Xaml1" runat="server" Width="200" Height="200" XamlUrl="~/Page.Xaml" />

        </div>

        <div>

            <input type="button" id="button1" value="Click Me" onclick = "onClickButton();" />

        </div>

    </form>

</body>

When pressing on the button, the JavaScript methos onClickButton() is called, and:

  • Get the Xaml control 'Xaml1'.
  • Call the Managed Acriptable method Hello().
  • Find the text block Xaml element "tb" and changed the text to "Hello Silverlight".

Before button clicked...

Silverlight JavaScript

After button clicked...

Silverlight JavaScript

The source code of Silverlight JavaScript.

Enjoy!

שלח תגובה

(שדה חובה)  

(שדה חובה)  

(אופציונלי)

(שדה חובה) 

Please add 8 and 5 and type the answer here:


Enter the numbers above: