Pages

Saturday, 27 July 2013

Call a WebService in ASP.NET using 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 :

<menuid="m01"value=”F23”>

<contextmenu>

<menuitemvalue=”Edit”name=”_edit” />

<menuitemvalue=”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.

publicclassWebService : System.Web.Services.WebService

{

public WebService ()

{

}

[WebMethod]

publicstring HelloWorld()

{

return"Hello World";

}

[WebMethod]

publicstring HelloMe(string Name)

{

return"Hello " + Name + " !";

}

[WebMethod]

publicbool CheckName(string Name)

{

// Checking for records can be done here.

return (Name == "Validator");

}

[WebMethod]

publicstring 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.

<asp:CustomValidatorID="cvName"ControlToValidate="txtCheckName"EnableClientScript="true"ClientValidationFunction="CheckForDuplicateInDB"runat="server"Display="Static"ToolTip="Name is Duplicate."Text="*"></asp:CustomValidator>