Monday, February 25, 2013

Calling Web Services from Javascript

This also quite straight simple and I am using Asp.Net. The requirement and the procedures are as stated below.
It might be helpful if compare with Calling Code behind Server function from Javascript.

1. Using Ajax.
2. Add ScriptManager or ToolkitScriptManager
3. And a new Web Services Assuming that returning List<string>.
public class MyWebService : System.Web.Services.WebService
{
[WebMethod]
    public List<string> GetData(string CatID)
    {
        List<string> list = new List<string>();
        if (CatID== "1")
        {
            list.Add("Nokia N95");
            list.Add("Nokia N70");
            list.Add("Nokia 6630");
        }
        else
        {
            list.Add("Dell Laptop");
            list.Add("HP Laptop");
            list.Add("Sony Laptop");
        }
        return list;
    }
}
4. Add javascript function as following.
<script type="text/javascript">
       function CallWS_onclick() {
         var catid = $get('<%= txtCatID.ClientID %>').value;
         MyWebService.GetData(catid , onSuccess, onFailed);
      }
      function onSuccess(result)
      {
          var Result= $get('<%= lblResult.ClientID %>');             
         Result.innerHTML = "";
            
         for(i=0 ; i<result.length ; i++)
         {
            Result.innerHTML += result[i] + "<br />";
         }
      }
      function onFailed(error)
      {
          var Result= $get('<%= lblResult.ClientID %>');
         Result.innerHTML = "Service Error: " + error.get_message();
      }
   </script>
5. Add one input button in design page.
<input id="Button1" type="button" value="Get Products"
      onclick="Button1_onclick(this)" /> 

That's it.
Enjoy Programming ! 
Ref:http://www.ezzylearning.com/tutorial.aspx?tid=3967791&q=calling-web-services-in-client-script-using-asp-net-ajax

No comments:

Post a Comment