Click here to Skip to main content
15,886,689 members
Articles / Web Development / HTML

JavaScript Objects to .NET WebMethods Expecting Type Object

Rate me:
Please Sign up or sign in to vote.
4.00/5 (3 votes)
23 Feb 2010CPOL4 min read 31.7K   406   17  
This article shows how to pass a JavaScript object to a .NET webservice that expects a parameter of type object.

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.

Screen_shot.png

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.

VB.NET
<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:

  1. 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:

    VB.NET
    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.

  2. Or with the UpdateProfileData as firstly defined.
    VB.NET
    'UpdateProfileData as fully defined
    <WebMethod(EnableSession:=True)> _
    	Public Function UpdateProfileData(ByVal anotherParameter As String, _
    	ByVal objCNameAddress As Customer) As String
    	'This customer object could be passed on to 
    	'somewhere else of use, but we'll just return a stringified version 
    		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.

JavaScript
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"; 	//Hard code some variables as we just display subset 
				//on the browser.
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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
Ireland Ireland
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --