The diary of a .NET Developer, working on an unlaunched startup project. Also, I live and work in Southern Oregon.

Showing posts with label Javascript. Show all posts
Showing posts with label Javascript. Show all posts

Tuesday, January 27, 2009

ASP.NET Ajax vs jQuery.ajax

I love jQuery but ASP.NET Ajax has some great features for calling your own webservices.  Using jQuery to call services is much simpler, and has less going on behind the scenes, but is harder to debug.  ASP.NET Ajax is creating a leaky abstraction for you, and along with that you get intellisense, helpful erorrs, and full visual studio debugging capabilities.

Calling ASP.NET Webservice with jQuery:

$.ajax({
type: "POST",
url: "PortfolioService.asmx/AddBenchmarkToCart",
data: '{portfolioId: "'+portfolioId+'", benchmarkId:"' + benchmarkId+ '", position:"'+position+'"}',
contentType: "application/json; charset=utf-8",
dataType: "json"});


Pros:
  • Simple code: not a lot of behind the scenes magic
  • Efficient: doesn’t load any extra javascript files
Cons:
  • Hard to debug: it either works or it doesn’t, you get no useful error messages
  • Six lines of code to copy/paste each time

Calling ASP.NET Webservice with ASP.NET Ajax:

<asp:ScriptManager ID="ScriptManager1" runat="server" >
<Services>
<asp:ServiceReference Path="~/Portfolio/PortfolioService.asmx" InlineScript="false" />
</Services>
</asp:ScriptManager>
PortfolioService.AddBenchmarkToCart(portfolioId, benchmarkId, position);
Pros:
  • Intellisense
  • Useful Error Messages
  • Fully functional visual studio debugging
Cons:
  • Less efficient: includes a small proxy javascript file for your webservice (which the client must download).

For more information on this, see this nice tutorial over on the asp.net site.

Javascript Class Definitions

Two ways to define a class in javascript.  

At first glance, I didn’t realize what was going on in the second example, but the code is just using JSON syntax to define the prototype.

The benefit of reading other people’s code is you always learn something new.

(I picked this up browsing through the jQuery source code.)

I placed the actual source code here so you can can see it in action.

This is the way I always defined classes:

    function Person2(name, age) {
this.name = name;
this.age = age;
}

Person2.prototype.HaveBirthday = function() {
this.age++;
}

Person2.prototype.GreetWorld = function() {
return "Hello World, my name is " + this.name + " and I am " + this.age + "years old";
}

A shorthand way using JSON syntax:

    Person.prototype = {
HaveBirthday: function() {
this.age++;
},

GreetWorld: function() {
return "Hello World, my name is " + this.name + " and I am " + this.age + "years old";
}
};

This makes a lot more sense when you realize you can even do this:

var ben3 = { 
age: 29,
name: "Ben",
GreetWorld: function() {
return "Hello World, my name is " + this.name + " and I am " + this.age + " years old"; },
HaveBirthday: function() { this.age++; }
};