Introduction
In .NET Framework 3.5 WCF supports returning JSON serialized data from REST-based Web Service. You can read REST Based WCF Service in ASP.NET 3.5 article to know about developing a REST Web Service. This post explains about creating a REST based Web Service that returns JSON-formatted data to ASP.NET page.
1.Create a new web site in VS20008 and Add a new item to the App_Code folder by selecting the AJAX-enabled WCF Service template from the dialogue box as shown below
2. Add a new method named GetAllEmployee() to the above created class file as follows
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.ServiceModel; using System.Runtime.Serialization; using System.Collections.Generic; using System.ServiceModel.Web; using System.ServiceModel.Activation; using System.Configuration; [OperationContract] [WebGet(UriTemplate = "/")] public EmployeeResults[] GetAllEmployee() { string strConnection = ConfigurationManager
.ConnectionStrings["AdventureWorksConnectionString"].ConnectionString; DataClassesDataContext dc = new DataClassesDataContext(strConnection); string strUrl = WebOperationContext.Current.IncomingRequest.UriTemplateMatch.RequestUri.ToString(); var result = from anEmp in dc.employee select new EmployeeResults { EmployeeName = dc.emp_name; Link = string.Format("{0}{1}",currentURL,dc.emp_name); } return result.ToArray(); }
We need to write a LINQ to SQL class for returning the employee details from the entity by exposing some properties like emp_name.
3. Add a new item to the web site and select the AJAX Web Form as the Template and name the web form as ShowEmployee.aspx as follows
4. Expand the ScriptManager element, add a Services element and then add a ServiceReference element along with a Path attribute as follows.
The path attribute value for ServiceReference element is .svc file in the project.
5. Write the following code in the ShowEmployee.aspx file
We are getting the reference of an employee and loop through the results and then populating the list of employee in drop down. Notice that the results is JSON encoded version array.
6. You will also get the IntelliSense for the EmployeeJSONService type inside the pageLoad() function.
7. View the ShowEmployee.aspx page in browser you will get the employee names in the drop down list.
Conclusion
This basic example explained about writing WCF service using AJAX code.
Share this post : |
[…] The above scenario makes use of an ASMX service, but you could just as easily be targeting an AJAX-enabled WCF service, which both have pretty similar semantics in this […]
great article .. missing endpoint behavior and binding information.
Please visit REST using WCF 4 post for more info