Oct 26 2006

ASP.NET and JQuery - first example

Posted by admin under Ajax

JQuery is another javascript library which eases javascript developemt - and it also (of course) includes some Ajax functionality. There are  a lot of cool client side plugins  and as soon as you have gotten the main Ajax communication working (not matter which helper library you choose), I bet you will soon enough be googling for cool GUI widgets as well so those are really worth a lot - at least for me. Compared to prototype and the like - JQuery also have a great website, containing good documentation and examples.

First of all - there are NO serverside components to reference from your VS project. Just a simple js file. It's up to you to handle how the data should be serialized and interpreted on both sides of the line (client and server). I will in later articles describe how that could be done.

Anyway, we need to start somewhere - and in the first example there is NO asp.net, no AJAX - just a simple HTML file - and some javascript. The reason for that is well, lets look at the example first:

When clicked a simple alert('Hello world') should be performed.

Code like this would be the "normal case":



<span style="background-color:LightBlue" onclick="alert('Hello world')" >Click me to update</span>


However with JQuery we have the possibility to work with elements in an unobtrusive way. Look at this JQuery variant of the code instead:



<script src="jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
	$('#clickmeupdate').click(function() {
		alert('Hello world!');
	});
});
</script>
<body>
    <form id="form1" runat="server">
    <div>
    <span style="background-color:LightBlue" id="clickmeupdate" >Click me to update</span>
...
...


Pretty elegant in my world at least.

It will also make it pretty nice to create an ASP.NET JQuery wrapper, working in the way of "extenders" instead of needing to subclass controls. We will look into that in a future article.