Using a HttpHandler and Attributes to call C# methods in Javascript

Michael Schwarz on Tuesday, February 15, 2005

Now, I am back and done a new sample on how to call C# (or simply .NET methods) from the client using Javascript. As you can see on my last posts I had done this using a IFRAME or the XmlHttpRequest object (yes, this is working in FireFox and Mozilla like it is working in Internet Explorer). But the main thing I had to do was to build small wrapper Javascript code, everytime the same way.

So, today I build a small sample to do this automatic. First of all I decided to add a HttpHandler that will allow to reach every class (method) in the ASP.NET application. The HttpHandler will take the requested URL which represents a class and the assembly.

http://localhost/Class1, ClassLibrary1.csjava [1]

The HttpHandler will check wether the class Class1 is available in the assembly ClassLibrary1. The Class1 will hold all my methods I need on one of my pages. I will include this Javascript file which is generated on the fly in my HTML (.aspx) file:

<script language="javascript" src="http://localhost/Class1, ClassLibrary1.csjava"></script>

But which method is put in the Javascript? I added a custom attribute to all of my methods that can be used in Javascript. See the following snippet of my class1.cs:

[CSJavaMethod(CSJavaMethodType.UseCallback)] public int Add(int a, int b) { return a+b; }

[CSJavaMethod(CSJavaMethodType.WithoutCallback)] public void DoAction(string line) { System.IO.TextWriter tw = System.IO.File.AppendText("c:\\csjava.txt"); tw.WriteLine(line); tw.Close(); }

The custom attribute CSJavaMethod will tell the HttpHandler if and how to put a wrapper in the Javascript file. There are two different types, one for invoking a method without any result and one that will use a callback function that will be called after finished the method.

In the HTML (.aspx) file we can call such methods as they were local Javascript functions:

<a href="javascript:DoAction('My sample line');void(0);">DoAction</a> <a href="javascript:Add(2, 4, callback_AddResult);void(0);">Add Test (2+4 = 6)</a> In the second HTML line we can see that we add a parameter for the callback. The callback is a simple Javascript function that will be called after finished the method.

<script language="javascript"> function callback_AddResult(res) { alert(res); } </script>

I do not have any sample running on public domains. If you wish to see it in action send me a short mail to dotnet @ schwarz-interactive .de.