Using jQuery To Call ASP.NET Page Methods and Web Services

by bigcarlito Wednesday, July 16, 2008

I'm a HUGE fan of jQuery.  In fact in my latest project, I've removed the ScriptManager from my ASP.NET pages entirely.  Originally I was including both jQuery and the ScriptManager on my pages because I just couldn't live without the ease and simplicity of calling page methods with ASP.NET AJAX. 

Well, with a little help from Dave Ward and Rick Strahl, I realized that calling ASP.NET page methods (and web services) from jQuery is really pretty simple. I haven't seen any one place where the exact code to do this is presented, so here is the code that I use to call page methods with jQuery: 

Step 1: Define your web methods in your code behind:

[WebMethod()]
public static int TestNoParams()
{
return 1;
}
[WebMethod()]
public static string TestWithParams(string a, int b)
{
return a + b.ToString();
}

Step 2: Include the jQuery library:

<script type="text/javascript"        src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js">
</script>

I also use the following (optional) helper function to call page methods:

<script type="text/javascript">
function PageMethod(fn, paramArray, successFn, errorFn)
{
  var pagePath = window.location.pathname;
  //Create list of parameters in the form:
//{"paramName1":"paramValue1","paramName2":"paramValue2"}
  var paramList = '';
  if (paramArray.length > 0)
  {
    for (var i=0; i<paramArray.length; i+=2)
    {
      if (paramList.length > 0) paramList += ',';
      paramList += '"' + paramArray[i] + '":"' + paramArray[i+1] + '"';
    }
  }
  paramList = '{' + paramList + '}';
  //Call the page method
  $.ajax({
      type: "POST",
      url: pagePath + "/" + fn,
      contentType: "application/json; charset=utf-8",
      data: paramList,
      dataType: "json",
      success: successFn,
      error: errorFn
  })
;}
</script>
*NOTE: It's possible to simplify this even more, but I prefer this because it closely emulates the way ASP.NET AJAX page methods are called.


Step 3:
Now in your Javascript code, you can easily call page methods like so:

PageMethod("TestNoParams", [], AjaxSucceeded, AjaxFailed); //No parameters
PageMethod("TestWithParams", ["a", "value", "b", 2], AjaxSucceeded, AjaxFailed); //With parameters

Step 4: Handle the result

function AjaxSucceeded (result)
{ 
alert(result.d);
}
Note that the parameter names ("a" and "b" in the above example) must match the variable names on your WebMethod exactly. Also notice in the success function that the actual data is in the 'd' property of the result.


That's it!  You can use the same kind of code to call ASP.NET web services, you just need to change the pagePath variable to the path of the .asmx file. 

Happy jQuerying! 

EDIT: I've updated it to show how to handle the result

 

Share/Save/Bookmark     kick it on DotNetKicks.com

Comments

DotNetKicks.com

7/17/2008 7:00:15 AM

trackback

Trackback from DotNetKicks.com

Using jQuery To Call ASP.NET Page Methods and Web Services

John S.

7/17/2008 8:35:47 AM

John S.

What's the advantage to passing a string array as opposed to just passing the object with parameters?

For example
PageMethod("TestWithParams", {b:"theresulthere"}, AjaxSucceeded, AjaxFailed); //With parameters

That gets rid of the overhead of processing the array (which I'm sure isn't much, but every little bit helps)

Joel

7/17/2008 9:44:40 AM

Joel

You're right, as I mentioned in the *NOTE, I do it that way because it's more familiar for me, but you could definitely do it as you suggest (although be sure to put quotes around your var name also) ;)

RaTT

7/18/2008 1:08:22 AM

RaTT

Cool, but what about d property of the result? Where does it come from? Why d?

Muhammad Mosa

7/18/2008 1:27:00 AM

Muhammad Mosa

When I tried to supply parameters to the called method using data option and not providing content length I got an error from IE. I faced that in IE only and on Live Demo, not in local development. Any ideas guys why this happen?!
Nice walkthrough Smile cheers

Janko

7/18/2008 5:00:38 AM

Janko

A good one, Joel!

Dave Ward

7/18/2008 8:39:45 AM

Dave Ward

@RaTT: The ".d" is a security feature added in 3.5. If you run this same code in an ASP.NET 2.0 site with v1 of the ASP.NET AJAX Extensions, it will come back directly in "result", without the ".d".

FrenchiInLA

7/18/2008 1:38:14 PM

FrenchiInLA

Mosa You can also use jason2.js method JSON.stringify. This method produces a JSON text from a JavaScript value. there is also a Jquery Plugin that does everything for you look for Jquery.ajaxDotNet.js. cheers

Sepideh

7/18/2008 2:44:35 PM

Sepideh

Its a very good way, but my question is How can I call a method in this static method, for example I have a none static method that I want save my new data into the database, How can I call it in this web service method, thanx

Joel

7/18/2008 5:50:15 PM

Joel

Sepideh, if you want to call a non-static method of an object you would first need to create the object and then call the method within the web method. A web service call is inherently stateless.

Sepideh

7/19/2008 8:45:53 AM

Sepideh

yes I did exactly what you say, but if I have in the nonestatic method something like a dropdown list or text box it terurn me an arror and fail, \
for axample
public partial class index :
[WebMethod]
public static string getText()
{
index aindex = new index();
aindex.callme();
return "true";
}

public void callme ()
{
int a= DrpAIncome.SelectedValue;
}
}

but in function AjaxSuccess(result)
{
alert(result.d);
}
method it alert(error)

can u tell me about it?tnx

Joel

7/19/2008 9:03:03 AM

Joel

Web method calls are stateless - that means it knows nothing about the page it's being called from. If you need the web method to do something based on the value of a dropdown on the page then you will need to send that value as an argument to your web method.

Sepideh

7/19/2008 9:52:14 AM

Sepideh

yes I got what you mean now, thanx alot Joel

Sepideh

7/21/2008 6:20:10 PM

Sepideh

hi Joel,
I have a gridview that by Eval bind some data to it?how can I change it in jquary?
tnx

Joel

7/21/2008 9:44:24 PM

Joel

I'm not exactly sure what you mean by 'change it in jQuery'? What do you want to change?

Sepideh

7/22/2008 8:34:12 AM

Sepideh

hi, you know that we usually use grid view and dropdown list in asp.net and bind data to it by eval, but I want to know if I want to user ajax and jquary , it doesnt load my grid view, I mean can I load my grid view by a method like PageMethod?I mean that I bind data to gridview by ajax or jQuery?

Sepideh

7/22/2008 8:39:38 AM

Sepideh

this is my code:
<asp:GridView ID="WallGrid" runat="server" AutoGenerateColumns="False">
<Columns>
<asp:TemplateField HeaderText="Creator">
<EditItemTemplate>
<asp:TextBox ID="TextBox1" runat="server" Text='<%# Bind("Creator") %>'></asp:TextBox>
</EditItemTemplate>
<ItemTemplate>
<asp:Label ID="Label1" runat="server" Text='<%# Bind("Creator") %>'></asp:Label>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

but how can I replcae this code with jQuary?
becuse my page can not be refreshed and should use ajax

Joel

7/22/2008 6:46:12 PM

Joel

The gridview is a purely server-side control, so if you need to 'ajaxify' it, the simplest thing would be to wrap it in an UpdatePanel. If you prefer to use jQuery I'd suggest trying one of the many client-side grids that are out there like:

http://www.webplicity.net/flexigrid/
http://reconstrukt.com/ingrid/

And there are many more if you search around. Good luck!

Remmrit Bookmarking

9/1/2008 8:30:50 PM

trackback

Trackback from Remmrit Bookmarking

Jquery Bookmarks

Programmatically Speaking ...

10/15/2008 9:52:35 AM

trackback

Trackback from Programmatically Speaking ...

Good links: ASP .NET and JQuery

Comments are closed