Saturday, 27 July 2013

Call a WebService in ASP.NET using JSON




What is JSON?
  JSON is JavaScript Object Notation – It is used for Data Interchange, Describes about format of data interchange. It is Light-Weight.

Example:
{“menu”: {
“id”: “m01”,
“value”: “F23”,
“contextmenu”:{
“menuitem”:[
{“value”: ”Edit”,”name”: “_edit”},
{“value”: ”View”,”name”: “_view”}
   ]
           }
}
}

In Xml :

<menu id="m01" value=F23>
  <contextmenu>
    <menuitem value=Edit name=_edit />
    <menuitem value=View name=_view />
  </contextmenu>

</menu>

Now we see the program how we are going to call a web service using JSON. Create ASP.NET WebService, with few WebMethods.

Step 1. Create  a  ASP.NET Application and add a webservice1.asmx as new item from visual studio and the following code to create a web service.


public class WebService : System.Web.Services.WebService
{

    public WebService ()
    {
       
    }

    [WebMethod]
    public string HelloWorld()
    {
        return "Hello World";
    }

    [WebMethod]
    public string HelloMe(string Name)
    {
        return "Hello " + Name + " !";
    }

    [WebMethod]
    public bool CheckName(string Name)
    {
        // Checking for records can be done here.
        return (Name == "Validator");
    }

    [WebMethod]
    public string CallError()
    {
        int i = 0;
        int j = 5 / i;    //Divide by Zero Error
        return "Error";
    }
}


Above service have four methods one method with no parameter, another method with parameter, another one is used to check validate the control and finally for exception.

Step 2. Create a JavaScript function to call the Web Service.

function SynchronousJSONResponse(url, postData)
    {
        var xmlhttp = null;
        if (window.XMLHttpRequest)
            xmlhttp = new XMLHttpRequest();
        else if (window.ActiveXObject) {
            if (new ActiveXObject("Microsoft.XMLHTTP"))
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            else
                xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        } 
        url = url + "?rnd=" + Math.random(); // to be ensure non-cached version 
        xmlhttp.open("POST", url, false);
        xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
        xmlhttp.send(postData);
        var responseText = xmlhttp.responseText;
        return responseText;
    }

   Above method is used to post the data to the web service and get the response from the web service.Check for the xmlhttp to initialize for which object.

Above service have four methods one method with no parameter, another method with parameter, another one is used to check validate the control and finally for exception.
The First Parameter consists of Url of Web Service including the Web Method.
The Second Parameter consists of Data that send as parameter using JSON.

Step 3: Create an event and bind it with JavaScript function.
     3.1 Simple Web Service call
        <dt>Simple Call</dt>
           <dt><a href="javascript:HelloWorld()">Hello World</a></dt>      
          function HelloWorld()
     {
var result = SynchronousJSONResponse('<%= Page.ResolveUrl("~/WebService.asmx/HelloWorld") %>'null);
           result = eval('(' + result + ')');
       alert(result.d);
    }

     3.2 Web Service Call with passing a parameter.
         In this a Link is binded to the Javascript function on click, In Which the function          takes the Value from the TextBox and pass as parameter to web method.

         <dt>Call With Paramter</dt>
            <dt><input id="txtName" value="Your Name" />
               <a href="javascript:HelloMe()">Hello Me</a>
            </dt>      
function HelloMe()
{
  var result = GetSynchronousJSONResponse('<%=                  
            Page.ResolveUrl("~/WebService.asmx/HelloMe") %>',
            '{"Name":"' + document.getElementById('txtName').value + '"}');        result = eval('(' + result + ')');
    alert(result.d);
}

     3.3 Binding the Web Method with Control Validate.
          In this We are validating a control using the Custom Validator by using the             client Script.Which invokes the webservice and validate the Value present in             TextBox.

        <dt>Call With Custom Validator</dt>
        <dt>
            <asp:TextBox ID="txtCheckName" runat="server" Text="Validator"></asp:TextBox>
            <asp:CustomValidator ID="cvName" ControlToValidate="txtCheckName"      
                EnableClientScript="true"              
                ClientValidationFunction="CheckForDuplicateInDB" runat="server"
                Display="Static" ToolTip="Name is Duplicate."           
                Text="*"></asp:CustomValidator>
            <asp:Button ID="btnClickMe" runat="server" Text="ClickMe!" />
            <a href="#" onclick="a()">a</a>
        </dt>

           function CheckForDuplicateInDB(sender, arg) {
var result = GetSynchronousJSONResponse('<%= Page.ResolveUrl("~/WebService.asmx/CheckName") %>''{"Name":"' + arg.Value + '"}');
                 result = eval('(' + result + ')');
                 arg.IsValid = !result.d;
                }

        function a() {
var result = GetSynchronousJSONResponse('<%=
Page.ResolveUrl("~/WebService.asmx/HelloMe") %>''{"Name":"' + document.getElementById('txtName').value + '"}');
       result = eval('(' + result + ')');
       alert(result.d);
                }
   

     3.4 Handle Server Error
         Handling the error on client side when it is raise on server side.

<dt><a href="javascript:CallError()">Call Error</a></dt>             

function CallError() {
var result = GetSynchronousJSONResponse('<%= Page.ResolveUrl("~/WebService.asmx/CallError") %>'null);
        result = eval('(' + result + ')');
        if (typeof (result.d) == 'undefined')
          alert(result.Message);
        else
          alert(result.d);
    }

The parameter is passed in JSON format, The Response from the Web Service is get and alerted in page.

Full ASP.Net Code.
Javascript 


<script type="text/javascript">

      function SynchronousJSONResponse(url, postData)
            {
                  var xmlhttp = null;
                 if (window.XMLHttpRequest)
                        xmlhttp = new XMLHttpRequest();
                 else if (window.ActiveXObject) {
                           if (new ActiveXObject("Microsoft.XMLHTTP"))
                                 xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
                          else
                                 xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
                              }   
                         url = url + "?rnd=" + Math.random(); // to be ensure non-cached version 
                        xmlhttp.open("POST", url, false);
                        xmlhttp.setRequestHeader("Content-Type", "application/json; charset=utf-8");
                        xmlhttp.send(postData);
                       var responseText = xmlhttp.responseText;
                       return responseText;
                 }

         function HelloWorld()
     {
var result = SynchronousJSONResponse('<%= Page.ResolveUrl("~/WebService.asmx/HelloWorld") %>'null);
           result = eval('(' + result + ')');
       alert(result.d);
    }
         function HelloMe()
{
  var result = GetSynchronousJSONResponse('<%=                  
            Page.ResolveUrl("~/WebService.asmx/HelloMe") %>',
            '{"Name":"' + document.getElementById('txtName').value + '"}');        result = eval('(' + result + ')');
    alert(result.d);
}
         function CheckForDuplicateInDB(sender, arg) {
var result = GetSynchronousJSONResponse('<%= Page.ResolveUrl("~/WebService.asmx/CheckName") %>''{"Name":"' + arg.Value + '"}');
                 result = eval('(' + result + ')');
                 arg.IsValid = !result.d;
                }

        function a() {
var result = GetSynchronousJSONResponse('<%=
Page.ResolveUrl("~/WebService.asmx/HelloMe") %>''{"Name":"' + document.getElementById('txtName').value + '"}');
       result = eval('(' + result + ')');
       alert(result.d);
                }
       function CallError() {
var result = GetSynchronousJSONResponse('<%= Page.ResolveUrl("~/WebService.asmx/CallError") %>'null);
        result = eval('(' + result + ')');
        if (typeof (result.d) == 'undefined')
          alert(result.Message);
        else
          alert(result.d);
    }

</script>


 ASP.NET Code :

<body>
    <form runat="server"> 
    <dl>
        <dt>Simple Call</dt>
        <dt><a href="javascript:HelloWorld()">Hello World</a></dt>
        <dt><hr /></dt>
        <dt>Call With Parameter</dt>
        <dt><input id="txtName" value="Your Name" />
            <a href="javascript:HelloMe()">Hello Me</a>
        </dt>
        <dt><hr /></dt>
        <dt>Call With Custom validator</dt>
        <dt>
            <asp:TextBox ID="txtCheckName" runat="server" Text="Validator"></asp:TextBox>
            <asp:CustomValidator ID="cvName" ControlToValidate="txtCheckName" EnableClientScript="true" ClientValidationFunction="CheckForDuplicateInDB" runat="server" Display="Static" ToolTip="Name is Duplicate." Text="*"></asp:CustomValidator>
            <asp:Button ID="btnClickMe" runat="server" Text="ClickMe!" />
            <a href="#" onclick="a()">a</a>  
        </dt>
     <dt><hr /></dt>
        <dt>Call Error</dt>
        <dt><a href="javascript:CallError()">Call Error</a></dt>
        <dt><hr /></dt>
    </dl>
    </form>
</body>


 I hope from this article you can learn basic information of how to call a web service from ASP.NET Website using JSON in ASP.NET