Calling ASP.NET Web Service Using Jquery - Part II - Passing Parameters

by Prashant 6. March 2010 03:35

In my previous post I have shown with a simple example on how you call an ASP.NET web service using JQuery. In this post I will show how you on how can you pass parameters to the web method and get the result using the web service.
If you have read my previous post, you have seen that we have just called a web method which returns a simple string back to us. In this example, instead of returning a plain simple string back to the client, we will ask the user to enter two numbers and the call the web service which in turn add the two numbers and returns the result back to the client.

First start up with the design of the page. As we are going to add two numbers, we will add a label, textboxes and a button as shown in the below screenshot:

Add a web service to your project as I have described in my previous post. Follow the same steps to add a web service to your project. The only change that you have to make is to add a method which accepts two numbers as parameters and return the sum of the two numbers. For your convenience, the method is as follows.

[WebMethod]
public int Add(int num1, int num2)
{
	return num1 + num2;
}

The script which I am using here to call the web service is the same as I have shown in my previous post, but the data parameter in the ajax function needs to be changed. When we are calling a web service which returns a normal string to us we can set the data parameter to blank. But this is not the case when we have to pass parameters to the web service to return the result. The data parameter in the Jquery ajax script goes something like this:

data: "{'num1': " + $("#txt_num1").val() + ", 'num2': " + ("#txt_num2").val() + "}"

In this parameter the ‘num1’ and ‘num2’ are the name of the parameters in the web service which we have to fulfill if we want the result from the web service. The parameter variable name should always remains the same as defined in the web service method. The parameters and their values are separated by a ‘:’( colon) and a ‘,’ (comma) is used to separate the parameters. The Jquery script $(“txt_num1”).val() will set the value to the parameter and then pass it to the web service method to get the result.

The code for Jquery script to call a web service in this example goes like this:

function CallService() {
            $("#lblResult").addClass("loading");
            $("#lblResult").html('');
            $.ajax({
                type: "POST",
                url: "Service.asmx/Add",
                data: "{'num1': " + $("#txt_num1").val() + ", 'num2': " + $("#txt_num2").val() + "}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess,
                error: OnError
            });

            function OnSuccess(data, status) {
                $("#lblResult").removeClass("loading");
                $("#lblResult").html(data.d);
            }

            function OnError(request, status, error) {
                $("#lblResult").removeClass("loading");
                $("#lblResult").html(request.statusText);

            }
        }

I have added a bit of CSS to show ajax loading style animation. I am not covering it here but sure I will in the later Jquery posts. In my next post I will cover on how to fetch data from the SQL Server using a web service.

Download: JqueryAjaxParams.zip (94.76 kb)

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags: , , ,

ASP.NET | Jquery


Comments (16) -

Ramon silva
Ramon silva Brazil
4/16/2010 11:56:52 AM #

Thank you. Your post was very helpful to me

Reply

Okesh
Okesh United Kingdom
7/13/2011 12:52:42 AM #

Thanks your part 1 and this post was really helpful.

Reply

SandeepK
SandeepK India
10/15/2011 2:24:00 AM #

syntax error:

this line is wrong:
data: "{'num1': " + $("#txt_num1").val() + ", 'num2': " + $("#txt_num2").val() + "}",

it should be:
data: "{num1:'" + $("#txt_num1").val() + "',num2: '" + $("#txt_num2").val() + "'}",

Reply

prashant
prashant India
10/15/2011 6:01:23 AM #

It is not an error. Have you checked the uploaded source code? If you got the above (the one you postes) working then it might be the version of the jquery that makes the difference. Let me know if this is the case!!

Reply

Brad
Brad United States
10/20/2011 11:20:56 AM #

very helpful, thanks!

Reply

kshitij
kshitij India
11/9/2011 9:14:21 AM #

its taking on numbers. i m passing string , it says , internal server error

Reply

prashant
prashant India
11/9/2011 6:46:26 PM #

How you are passing the parameters and what is the return type of the web method? If you are using the above code and calling Add method while passing strings as a parameter then there would be an error because the Add method will return the sum of two numbers and not strings. If you want to pass the string then change the return type of the method and also the parameters to type string.

Reply

Didi
Didi United States
12/1/2011 12:54:44 PM #

How about if the method has no return it just takes an int param and do update on database? the code here doesn't seem to work, what changes should i make?

Reply

Prashant
Prashant India
12/1/2011 7:19:02 PM #

You need to change the Web Method in the service. Make the return type as void and write the update or delete statements as per your requirement. If you are getting some errors let me know.

Reply

Moien
Moien Iran
1/19/2012 4:15:11 AM #

i am dowload your project it is very good sample for basic developers . tanx for article

Reply

manish
manish India
1/23/2012 8:28:14 PM #

nice explanation

Reply

samir
samir India
2/2/2012 9:02:38 AM #

service is not get called on button click as per the part-I post

i have created a asp.net web application then copied code to default.aspx as provided in you page including button and label creation and also added onclientclick for button.
also added javaScript  provided under head tag.
added a new webservice.asmx and tried to call Helloworld method of service by button click but its not working..
pls suggest !!!

Reply

Prashant
Prashant India
2/2/2012 8:18:29 PM #

How you are getting the client ID of the asp button? In my examples I have used normal HTML button and the used the ID in the jQuery (as you can see above). But if you are using the server side button then you have to get the client ID and then use it in the jQuery.

Let me know of there is any other problem you are facing!

Reply

Dhiraj
Dhiraj India
3/29/2012 8:18:56 PM #

How to pass an complex object instead of just two parameters. Suppose we create a class in c# which has 10 fields i can't use the Add method with 10 parameters. I have created an entity class with those fields. I want the Add method to accept just one paramater of that class type.

Reply

Avadhesh Maurya
Avadhesh Maurya India
4/5/2012 12:40:53 AM #

I have asp page and i want to call this page webmethod using class object ,so how to pass parameter using jquery ajax method
please help me.......

Reply

Prashant
Prashant United States
4/6/2012 5:42:45 AM #

Are you saying that the web method is on the page?

Reply

Pingbacks and trackbacks (2)+

Add comment




  Country flag
biuquote
  • Comment
  • Preview
Loading


Visit blogadda.com to discover Indian blogs Computers Blogs

About Me

Name of authorPrashant Khandelwal.
Programmer and tech enthusiast. More...

Feeds Subscribe Twitter Facebook Google Plus Linked In Delicious

Badges

MVB

MVP Blog Badge.

HTML5 Powered with CSS3 / Styling, Graphics, 3D & Effects, Multimedia, Performance & Integration, Semantics, and Offline & Storage

Month List

Blog Stats

414,237 Hits

Adverts

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

© Copyright 2012

Creative Commons License