Call Scribtable Methods from JavaScript with Silverlight
Today I wrote a very simple example how to call a C# method from JavaScript code. I was using this because I'd like to access the IsolatedStorage with a small wrapper that is working similar to the registry.
For this demo I will only use a very simple method like below:
string SayHello(string name) { return "Hello " + name; }
Note: only simple types (strings, bool, etc.) can be exposed. If you want to use your own object you have to use the JSON serialization. (Thanks to Luis Abreu for this comment!)
The [Scriptable] Attribute
Ok, what do I need to get this accessible from JavaScript code? First, I put this method in the Page.xaml.cs as a public method. To indentify that this method is accessible I added the [Scriptable] attribute to the class and the method itself. You may remeber this attribute from ASP.NET AJAX or Ajax.NET Professional ([AjaxMethod]).
[Scriptable] public class Page: Canvas { public Page() { Loaded += new EventHandler(Page_Loaded); } void Page_Loaded(object sender, EventArgs e) { } [Scriptable] public string SayHello(string name) { return "Hello " + name; } }
To register all scriptable methods you have to call a register method, again it is very similar to Ajax.NET Professional. In Page_Loaded you add following line:
WebApplication.Current.RegisterScriptableObject("basic", this);
Now, we switch to the JavaScript code and have a look how you can access these methods. I have created the Silverlight control with the ID SilverlightControl:
function createSilverlight() { Sys.Silverlight.createObjectEx({ source: "Page.xaml", parentElement: document.getElementById("SilverlightControlHost"), id: "SilverlightControl", properties: { background: "#000000", width: "1", height: "1", version: "0.95", enableHtmlAccess: true }, events: {} }); }
This code creates the ActiveX control with the ID SilverlightControl. In JavaScript you can access this control with document.getElementById("SilverlightControl"). The object you get will have a property Content. Attached to this object the RegisterScriptableObject will add a new property basic (see the call above, the first argument is used for the name) where you then can access the methods.
var control = document.getElementById("SilverlightControl"); var res = control.Content.basic.SayHello("Michael Schwarz");
In variable res you will have now "Hello Michael Schwarz".
3 Comments
Comments have been disabled for this content.
Wyatt said
How do you call a server C# method from silverlight? So if I have an assembly on the server that contains the SayHello method, how would I call that from Silverlight and not require the special SayHello assembly from being downloaded to the browser?
Michael Schwarz said
Hi Wyatt, you can use Web Services or AJAX requests to get data from your Web Server. I will post a example this week, so please check my blog.
Jeff Atwood said
Thanks Michael! This was very helpful-- you rock!!