Thursday, March 17, 2011

Calling ASP.NET WebMethod with more than one paramaters using JSON

Suppose we have a web method in ASP.NET web form or webservice

 [WebMethod]   
 public void GetItems(string itemName, string itemDesc)
 {

 }

 Using jQuery, we are going to call this method using the code like this below. I am pre-suming there is a search button which we have assigned id #searchNow
 

 $(document).ready(function () {  
  $('#searchNow').click(function () {
  $.ajax({
     type: "POST",
     url: "SearchItems.aspx/GetItems",
     data: "{'itemName':'book','itemDesc':'toys'}",
     contentType: "application/json; charset=utf-8",
     dataType: "json",
            success: function (msg) {
           
            }
        });
 });
  Our interest is how to pass parameters to the web method.
 In the snippet above the line


 data: "{'itemName':'book','itemDesc':'toys'}",

is used to pass parameters to the GetItems function. Please not that it must be a JSON compliant string