Web Service in ASP.NET
This article explains how to return JSON and XML data from a [WebMethod].
First we need to create a Web service as was already discussed in Part 1. Again create a new Web Service in Visual Studio.
Step 1
Step 1
Open Visual Studio and select "File" -> "New" -> "Web Site...".
Step 2
Step 2
Now add a Web Service file (.asmx) to the Web site.
Provide a name for the web service file.
And delete the existing code file from the Solution Explorer so that we can create our own class file to host on this web service.
Step 3
Provide a name for the web service file.
And delete the existing code file from the Solution Explorer so that we can create our own class file to host on this web service.
Step 3
Now add a new class file to [WebService] and also a class for a user data type to define the structure.
[WebSerivce] Class
User-define data type for JSON and XML Stucture:
Step 4
[WebSerivce] Class
User-define data type for JSON and XML Stucture:
Step 4
Edit the Employee Class and declare a property that we need to use in the JSON and XML object.
Code:
Code:
- public class Employee
- {
- public int Id { get; set; }
- public string Name { get; set; }
- public int Salary { get; set; }
- }
Step 5
Now edit your .asmx file to define the CodeBehind and Class Properties.
Step 6
Step 6
Next we need to create a [WebService] class MyServiceClass and add all the namespaces first that are required.
Step 7
Step 7
Write the [WebService] attribute over the class name and create the [WebMethod].
- GetEmployeeXML() for returning the data in XML.
- GetEmployeeJSON() for returning the data in JSON.
Code:
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Services;
- using System.Web.Script.Services;
- using System.Web.Script.Serialization;
- [WebService]
- public class MyServiceClass
- {
- [WebMethod]
- public Employee[] GetEmployessXML()
- {
- Employee[] emps= new Employee[] {
- new Employee()
- {
- Id=101,
- Name="Nitin",
- Salary=10000
- },
- new Employee()
- {
- Id=102,
- Name="Dinesh",
- Salary=100000
- }
- };
- return emps;
- }
- [WebMethod]
- [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
- public string GetEmployessJSON()
- {
- Employee[] emps = new Employee[] {
- new Employee()
- {
- Id=101,
- Name="Nitin",
- Salary=10000
- },
- new Employee()
- {
- Id=102,
- Name="Dinesh",
- Salary=100000
- }
- };
- return new JavaScriptSerializer().Serialize(emps);
- }
- }
Step 8
Build the application and view the output in a web browser.
There are two methods, one from the return of JSON and the second for the return of XML result.
Click on any function name and Invoke to test the [WebMethod].
There are two methods, one from the return of JSON and the second for the return of XML result.
Click on any function name and Invoke to test the [WebMethod].
- Click on GetEmployessJSON
- Click on GetEmployessXML
Thank you for reading this article.
No comments:
Post a Comment