16 marzo 2010

Calling ASP.net AJAX services from jQuery with unknown generic parameters

I love REST web applications and I must thank Dave Ward with his Encosia blog that introduced me to this kind of architecture.

Recently I had to do a function in common script that calls some web services and I used json object approach to solve this (see Simplify calling ASP.NET AJAX services from jQuery for more info).

All worked fine but I had to pass different params to different services without making custom class for every specific javascript object.


Example:

var data = new Object();
data.Param1Int = 1;
data.Param2String = "hello";
data.Param3Decimal = 2.5;

var param = new Object();
param.p = data;

$.ajax({
   url: '/Service.asmx/DoSomething',
   data: JSON.stringify(param),
   success: function(msg){ ... }
});

This is the jQuery AJAX call to my service... and in this case I need to pass three params.

I could pass to the "DoSomething" service the "data" object directly and in this case ASP.net expects a method like this:

[WebMethod]
public string DoSomething(Int32 Param1Int, String Param2String, Decimal Param2Decimal)
{ ... }

But if I need to add another param or I don't know exactly how they are?

So I wrapped the "data" object in another one... "param" with his member "p".
In this case my web method changed in:

[WebMethod]
public String DoSomething(Dictionary<string, string> p)
{
   Int32 Param1Int = Convert.ToInt32(p["Param1Int"]);
   String Param2String = Convert.ToString(p["Param2String"]);
   Decimal Param3Decimal = Convert.Todecimal(p["Param3Decimal"]);
   ...
}

With Dictionary-based parameters you can pass to your web service every kind and as many params as you want.