Consuming Web Service using ASP.NET AJAX Part II
by David Hayden ( Microsoft MVP C# ), Filed: ASP.NET 2.0
ASP.NET AJAX IN ACTION showed up on my doorstep late last night, and I was able to get through the first 5 chapters to make sure I was calling a web service appropriately from the browser using client-side AJAX. I am happy to report that I am doing it correctly as mentioned in my previous article:
Calling Web Services using Client-Side ASP.NET AJAX for Server-Side Validation
However, I could take advantage of the ASP.NET AJAX Javascript libraries more, which offers 1) more abstraction from browser Javascript differences, 2) a client-side page lifecycle similar to the ASP.NET Page Lifecyle, and 3) a number of the helper methods to add and remove handlers, etc. Pretty interesting stuff actually that is probably more appropriate for more advanced pages, etc., but here is a rewritten version of the Javascript code to use the more ASP.NET AJAX Style of development:
<script language="javascript" type="text/javascript">
function pageLoad() {
$addHandler($get('Text1'),'blur',CheckUrl);
}
function pageUnload() {
$removeHandler($get('Text1'),'blur',CheckUrl);
}
function CheckUrl () {
ValidatorService.ValidateUrl(
$get("Text1").value, OnComplete);
}
function OnComplete (arg) {
if (!arg)
$get("UrlExists").innerText = 'Invalid Url.';
else
$get("UrlExists").innerText = '';
}
</script>
The code nows takes advantage of the pageLoad and pageUnload events that are part of the client-side page lifecycle to add and remove handlers to the Text1, which is the textbox where want enters the URL. Rather than using the document.getElementById I can use the $get helper function that does the same thing, but abstracts out any differences in the DOM as well as keeps your Javascript code a bit smaller. The rest is probably self explanatory.
Now that I am attaching handlers to the Text1 TextBox in the Javascript, I can remove the onBlur attribute on the TextBox itself, which I had in the previous post.
Before:
<input
id="Text1"
onblur="javascript:CheckUrl();"
style="width: 319px"
type="text" />
After:
<input
id="Text1"
style="width: 319px"
type="text" />
Nothing else in the post changes. Both solutions work and give you that more performant real-time validation of the URL typed into the textbox by avoiding a partial-page postback:

Is it worth all the effort given that one could use an UpdatePanel or the ServerSideValidationExtender? I don't think one can answer that statement without understanding the needs of the project as a whole, but it sure is cool to see how one can do the validation with very little network traffic.
News Feed: David Hayden ( Microsoft MVP C# )
Filed: ASP.NET 2.0