Passing Dictionary From JavaScript to ASP.NET Web Service

The ASP.NET project that I’m currently working on uses AJAX to save data to a Web Service.  The web service is generic.  The web page should be able to pass address, phone numbers, sales info and etc to the web service.  Base on the key that is also passed to the web service, the web service should know how to save the data.
 
The first version of the client code that called the web service gathered all the data from the form and created a string that was pipe delimited.  Example: key=person|keyid=333323|firstname=John|lastname=Handcock.   When this information arrives at the web service it must be parsed and saved. A lot of red flags seem to pop up with this design.
 
Here’s the web service signature or the first version
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet=false)]
public string Save(string input)
 
There will always be a few fields that will be passed (key and keyID) to the web service.  The problem is that data fields (firstname, lastname, address and etc) could be different.  I figured out that I could add .NET Dictionary type to as a parameter to web service call.  The problem now is how do I gather and pass this information from the client javascript.
 
Here’s the the new save method web service
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet=false)]
public string Save(string key, string keyID, Dictionary<string, string> inputNameValue)
 
I could use the following JavaScript to pass data to the web service and it works, but the data values (first, last) need to be created dynamically. 
MoFormSave.Save(key, keyID, {"first":"john","last":"handcock"})
 
I tried to create an array that accepts an NameValue object and pass the object to web service, but this errors when I call the web service.  I finally figure out I could do the following and pass the object to the web service.
 
   var nameValue = {}; //new, empty object
   nameValue[‘first’] = ‘John’;
   nameValue[‘last’] = ‘Handcock’;
   MoFormSave.Save(key, keyID,  nameValues)
 
 
Resources:
Quick guide to somewhat advanced JavaScript – tour of some OO features
 
 

1 thought on “Passing Dictionary From JavaScript to ASP.NET Web Service”

Leave a Reply

Your email address will not be published. Required fields are marked *