Passing Parameters as Primitive Types:
The server side InsertCustomer methods is shown below:
This will work as expected and you will receive all the three arguments in your WebMethod. The problem arises when the list of arguments to pass increases. In that case you will have to increase the number of parameters for your InsertCustomer method which sounds like a bad idea. It is always a good programming practice to have minimal number of parameters for your methods. If the method is taking lots of parameters then you should always replace them with a single class instance.
The question is what parameter type should be use for InsertCustomer method. Let's try with the System.Object type and see how it behaves. The implementation below shows the updated InsertCustomer method that takes "Object" as an input parameters.
Since now you know that the object passed is of type Dictionary<String,Object> so you can replace the object with Dictionary<String,Object>. But instead of going down that path let's see if we can find a different way.
We have created a CLR class called Customer with FirstName, LastName and Age properties as shown below:
We updated the InsertCustomer method to take the CLR Customer object as an argument as shown below:
The result is shown below:
Using the Dynamic Keyword in .NET 4.0:
If you are using VS2010 then you can also make use of the dynamic keyword. The dynamic keyword will end up being a Dictionary<String,Object> object and you will have to use Name,Value pair to access the values as shown below:
Please note that in this article we used the Microsoft Ajax framework for sending Ajax request. In the next post we will check if the same behavior exists when using JQuery Ajax framework.