Use C# To Write Javascript?

posted on 03/04/06 at 10:14:11 pm by Joel Ross

Ever since I started writing web apps, I've realized that there's a huge need to be able to write solid Javascript. Even when ASP.NET launched, there was still a huge need to know Javascript - despite the claims you heard. I'm hearing a lot of the same claims now that ASP.NET 2.0 is out - not quite as much, but they're still there, despite the proliferation of AJAX. Obviously, the need for Javascript is not going away.

Well, given that Javascript seems to be such a touchy language, and is dependant (to an extent) on the browser the user is using, why isn't there an extension to the .NET framework that allows us to write our Javascript functions in a language familiar to us, such as C#? It seems to me that it wouldn't be that difficult to manage. The framework already does this for things right now - the Atlas framework handles the differences between the XmlHttp objects in IE and Firefox. Why can't this be extended to allow us to write our own "client-side" methods from the server - and have the framework translate to javascript for me?

Here's an example of what I'm talking about:

[ClientMethod]
public void ChangeText(string text)
{
?? MyLabel.Text = text;
}

Then on a button:

MyButton.OnClientClick += new ClientMethodEventHandler(ChangeText(MyTextBox.Text));

Obviously, you would have MyTextBox on the page somewhere.

On the client side, this would all get translated. First, the method:

function ChangeText(text)
{
?? document.getElementById('MyLabel').value = text;
}

This works in most cases, which is good, but what if MyLabel is in another control? By translating on the server side, it would be able to do that for you, so if MyLabel was in a user control (MyUserControl), it would spit out this:

function ChangeText(text)
{
?? document.getElementById('MyUserControl_MyLabel).value = textl
}

And yes, I know you should check to see if it can find the control first, but I'm just illustrating a point. As for the the client click event, it would render a button like so:

<input type='button' id='MyButton' onClick="javascript:ChangeText(document.getElementById('MyTextBox').value);" Text="Click Me" />

And of course, if MyTextBox is in MyUserControl, it would render as 'MyUserControl_MyTextBox'.

To me, this seems like a much easier way to write client code - for a couple of reasons. First, you're writing it in a language that you are more familiar with, so it'll be easier to write in the first place. Second, you're protected against change. When .NET 5.0 and IE 13 are using JoelScript as the scripting language, your code still works - because the framework generates the client script for you - in the best client script for the task!

Thoughts? Yes? No? Should I send this to the Framework team?

Technorati Tags: | |

Categories: ASP.NET