Introduction
This article shows how to pass a JavaScript object to a .NET webservice that expects a parameter of type object. JSON is an enormously powerful and lightweight way to send data to and from a webservice, however if there are a number of parameters that are needed to be sent to webservice, building a JSON string can be a pain, and having to set your webmethod to expect a matching number of parameters can be equally as painful. This article shows how to build and pass a JavaScript object "Customer
" and pass it to a .NET webservice webmethod that is expecting an object of type "Customer
".
Background
The example I've put together uses 3 basic components from the YUI Library. The components are Connection manager, Event and JSON. Links to these files are to external .js files, so once you are connected to the internet, the sample code should just work. I could go into why I've opted for YUI (Yahoo's JavaScript library), a brilliant JavaScript library with some of the best front end engineers at its helm, over AJAX.NET considering I'm writing to an ASP.NET page. Well the short story is, I don't use ASP.NET controls or AJAX.NET, I do use regular standard input boxes, etc. and DOM. I've also used document.getElementById
as opposed to the YUI or my own shorter version of it as it saves typing but here it should make it clear what I'm doing.
The sample code could as easily work if default.aspx was default.html however the webservice can be protected with a Session Variable created in the .ASPX page and then accessed by including the following <WebMethod(EnableSession:=True)>
_ when declaring the webmethod <=true)>
. I would normally use a secondary webservice, referenced in my website project, and make calls from the website webservice to the secondary webservice, as this webReferenced webservice will never be visible in JavaScript code on the client and therefore is not exposed. However, that's not what this article is about.
What Happens
When you fire up the project attached, the default page should load, which has an onload event that calls the './WebService.asmx/GetProfileData' webmethod. In this webmethod, we create a Customer
object and then using the ToJSON
function of the JSONHelper
class as referenced by this article and we return a JSON String from our Customer
Object. This JSON is processed on the client and populates the relevant textboxes.
Using the Modify button, the user is given the option to Save the modifications. It's the Save button that fires the event that creates a JavaScript object from the values in the textboxes. The object is then stringified and sent to the UpdateProfileData
as a customer
object.
Using the Code
In the project, we have defined a customer
class in Customer.vb.
The onload
event makes a call to get the customer details, with the webmethod GetProfileData
the successHandler
of this call displays in an alert before the values are loaded into the relevant textboxes.
The update webmethod UpdateProfileData
expects two parameters, one is a string
and one is an object of type Customer
as defined in Customer.vb.
<WebMethod(EnableSession:=True)> _
Public Function UpdateProfileData(ByVal anotherParameter As String, _
ByVal objCNameAddress As Customer) As String
The customer
object has a number of properties: TitleID, First Name, Last Name, Address details, a Boolean as whether the Customer
is a company, etc.
There are two ways to send this type of data to a webmethod:
- We could concatenate a JSON String of Parameters like so:
makeRequest.getDetails('./WebService.asmx/UpdateProfileData', Callback, _
'{"anotherParameter":"something", FirstName:"'+FirstName+'", _
LastName:"'+ LastName +'", Address1:"'+ Address1 +'", Address2:"'+ _
Address12+'", Address3:"'+ Address3+'"}');
where our webmethod would look like:
WebMethod(EnableSession:=True)> _
Public Function UpdateProfileData(ByVal anotherParameter As String, _
ByVal FirstName As String, ByVal LastName As String, ByVal Address1 As String, _
ByVal Address2 As String, ByVal Address3 As String) As String
You can see how difficult this could be, how awkward to build and make sure the syntax is correct.
- Or with the
UpdateProfileData
as firstly defined.
<WebMethod(EnableSession:=True)> _
Public Function UpdateProfileData(ByVal anotherParameter As String, _
ByVal objCNameAddress As Customer) As String
Dim JSONify As New JSONHelper
Return JSONify.ToJSON(objCNameAddress)
End Function
On the save event, we create our JavaScript object, we stringify it and then pass it to our webservice.
Create the JavaScript object and send it to the webmethod. As our webmethod expects two parameters, we pass the first parameter of type String
and the second parameter of type Object
.
var obj = {};
obj.Address1 = document.getElementById("Address1").value;
obj.Address2 = document.getElementById("Address2").value;
obj.Address3 = document.getElementById("Address3").value;
obj.City = document.getElementById("City").value;
obj.CompanyName = "Company Name";
obj.ContactName = "Contact Name";
obj.County = document.getElementById("County").value;;
obj.CustomerOwner = "Customer Owner";
obj.DOB = "DOB";
obj.EmailAddress = document.getElementById("EmailAddress").value;
obj.FirstName = document.getElementById("FirstName").value;
obj.IsCompany = false;
obj.LastName = document.getElementById("LastName").value;
obj.PhoneDay = document.getElementById("PhoneDay").value;
obj.PostalCode = document.getElementById("PostalCode").value;
obj.TitleID =3;
var jsonStr = YAHOO.lang.JSON.stringify(obj);
objCNameAddress = '{"anotherParameter":"somevalue",objCNameAddress:'+ jsonStr +'}';
makeRequest.getDetails('./WebService.asmx/UpdateProfileData',
updateContactDetailsCallback, objCNameAddress);
The callback successHandler
for the UpdateProfileData
is the same as that of the onload
event so we are again presented with an alert. If we have made any modifications, these will be visible here, before the response again populates the relevant textboxes.
I haven't gone into editing the web.config but there are a number of things to set up to allow use of .asmx and JSON serialization, however all is set up in the sample code for this to run.
History
- 20th February, 2010: Initial post
- 24th February, 2010: Article updated