:::: MENU ::::

Thursday, July 24, 2008

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?

  1. [WebMethod()]  
  2. public static int TestNoParams()  
  3. {  
  4. return 1;  
  5. }  
  6. [WebMethod()]  
  7. public static string TestWithParams(string a, int b)  
  8. {  
  9. return a + b.ToString();  
  10. }  
[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?

  1. <script type="text/javascript"         
  2. src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js">  
  3. </script>  
<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?

  1. <script type="text/javascript">  
  2. function PageMethod(fn, paramArray, successFn, errorFn)  
  3. {  
  4.   var pagePath = window.location.pathname;  
  5.   //Create list of parameters in the form:  
  6. //{"paramName1":"paramValue1","paramName2":"paramValue2"}  
  7.   var paramList = '';  
  8.   if (paramArray.length > 0)  
  9.   {  
  10.     for (var i=0; i<paramArray.length; i+=2)  
  11.     {  
  12.       if (paramList.length > 0) paramList += ',';  
  13.       paramList += '"' + paramArray[i] + '":"' + paramArray[i+1] + '"';  
  14.     }  
  15.   }  
  16.   paramList = '{' + paramList + '}';  
  17.   //Call the page method  
  18.   $.ajax({  
  19.       type: "POST",  
  20.       url: pagePath + "/" + fn,  
  21.       contentType: "application/json; charset=utf-8",  
  22.       data: paramList,  
  23.       dataType: "json",  
  24.       success: successFn,  
  25.       error: errorFn  
  26.   })  
  27. ;}  
  28. </script>  
<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?

  1. function AjaxSucceeded (result)  
  2. {   
  3. alert(result.d);  
  4. }  
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

 

More

Categories: