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:
view plaincopy to clipboardprint?
- [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:
view plaincopy to clipboardprint?
- <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:
view plaincopy to clipboardprint?
- <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
view plaincopy to clipboardprint?
- 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