Consuming a WCF Data Service using ASP.NET
by
Jagadish Pulakhandam
on
2/13/2012 1:58:21 PM
|
This article introduces the following:
- How to consume an already hosted OData Service (created using WCF Data Services)
- By connecting through Northwind OData Service hosted by Microsoft
- How to fetch data using LINQ from Data Service client
- How to Bind OData Service data to GridView
Following are the steps:
- Using Visual Studio 2010, create a new "ASP.NET Empty Application" Project ("ODataConsuming01" in this case)
- Right click on "References" and choose "Add Service Reference"
- Provide service url and Namespace details as follows (http://services.odata.org/Northwind/Northwind.svc/):
- Add a new web form to the project (WebForm1.aspx in this case)
- Drag a GridView and make sure that the markup looks like the following:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="ODataConsuming01.WebForm1" %>
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="gvCustomers" runat="server">
</asp:GridView>
</div>
</form>
</body>
</html>
- Write code-behind as shown below:
01.using System;
02.using System.Collections.Generic;
03.using System.Linq;
04.using System.Web;
05.using System.Web.UI;
06.using System.Web.UI.WebControls;
07.
08.using System.Data.Services.Client; //necessary to work with Data Services client
09.using ODataConsuming01.NorthwindSvcRef; //referring the proxy (or service client)
10.namespace ODataConsuming01
11.{
12. public partial class WebForm1 : System.Web.UI.Page
13. {
14. protected void Page_Load(object sender, EventArgs e)
15. {
16. //create the context (also called proxy or service client or client instance)
18.
19. //issue OData query using LINQ
20. var q = ctxt.Customers.Select(o => new {
21. Id = o.CustomerID,
22. Name = o.ContactName
23. });
24.
25.
26. //execute query and assign the results to GridView
27. gvCustomers.DataSource = q.ToList(); //the request to service is sent during the execution of this statement
28. gvCustomers.DataBind();
29. }
30. }
31.}
- Execute the application and you should see the output as shown below:
|
Join the .NET Code
Central Community and join the discussion!
Signing-up is FREE and quick. Do it now, we want to hear your opinion
|
|
|
|
Rated 0 from 0 votes
(
login
to rate)
|
|
|
|
|
|
|
|