SIGN UP MEMBER LOGIN:    
ARTICLE

Accessing a WCF Service in an ASP.Net MVC Application

Posted by Krishna Garad Articles | ASP.NET MVC with C# January 27, 2012
In this article we will see how to access a WCF service and use it in our ASP.Net MVC application.
Reader Level:
Download Files:
 

Introduction

In this article we will see how to access a WCF service and use it in our ASP.Net MVC application. In my previous articles we have seen the creation and consumtion of WCF services by a console client and a WPF client. In this article we will create the client as a MVC application.

For creating a WCF service you can read more over here. For this article we will create one simple WCF service which will return the dataset and in the MVC application we will simply access this WCF service and display the list of authors on the View. So let's start by creating the WCF service.

Creating WCF Author Service

Create a new WCF project in Visual Studio and name it AuthorService. When the service is created a default service will be created; delete it and add a new service to the project and name it ServiceAuthor which will create an 
IServiceAuthor Interface and a ServiceAuthor.cs class. Define one method in IServiceAuthor which returns a Dataset and in ServiceAuthor.cs implement the method which returns the dataset like below. Here I'm creating it on the fly but you can populate it from a database.

IServiceAuthor Code

public interface IServiceAuthor
{
     [OperationContract]
     void DoWork();
     [OperationContract]
     DataSet ReturnAuthor();
}


ServiceAuthor.cs

   
public class ServiceAuthor : IServiceAuthor
    {
        public void DoWork()
        {

        } 
        public System.Data.DataSet ReturnAuthor()
        {
            DataSet ds = new DataSet();            DataTable dt = new DataTable("Author");
            DataColumn dc1 = new DataColumn("AuthorId"typeof(Int32));
            DataColumn dc2 = new DataColumn("Name"typeof(string));
            DataColumn dc3 = new DataColumn("Location"typeof(string));
 
            dt.Columns.Add(dc1);
            dt.Columns.Add(dc2);
            dt.Columns.Add(dc3);
            DataRow dr1 = dt.NewRow();
            dr1[0] = 10;
            dr1[1] = "Krishna Garad";
            dr1[2] = "India";
            dt.Rows.Add(dr1);
            DataRow dr2 = dt.NewRow();
            dr2[0] = 20;
            dr2[1] = "Mahesh Chand";
            dr2[2] = "USA";
            dt.Rows.Add(dr2);
            ds.Tables.Add(dt);
            return ds;
        }
    }

Now run the service application and copy the address.

Creating MVC client Application

Start a new MVC web application; add the controller in the controller folder with the name Home. Now add the service reference by right-clicking on the solution and selecting Service Reference and paste the copied address in the address box in the opened dialog like below.

wcfwithmvc.gif

Now we also have a service reference, so create the proxy for our WCF service like below in the Home controller.

ClientAuthorReference.ServiceAuthorClient obj = new ClientAuthorReference.ServiceAuthorClient();

Still now we have a proxy for our WCF service; now we can call the methods of our WCF service. On start up only we will show the AuthorList return from WCF service so in the Index Action write the following code and add the view to display the List of Authors.

public ActionResult Index()
{
     DataSet ds = obj.ReturnAuthor();
     ViewBag.AuthorList = ds.Tables[0];
     return View();
}

Add a view to display the list of Authors by looping over the DataTables which we supplied to ViewBag. Write the following code in your aspx page.

<table>
        <tr><td>AuthorId</td><td>Name</td><td>Location</td></tr>
<%foreach (System.Data.DataRow dr in ViewBag.AuthorList.Rows)
  {
%>
    <tr>
 <td><%=dr["AuthorId"].ToString()%></td>         
         <td><%=dr["Name"].ToString() %></td
>
<td><%=dr["Location"].ToString() %></td>
    </tr>         
 <% } 
%>
 </table>

In the above markup we are simply reading each row and displaying on the page. Now run the application and view the Author List returned from WCF service.

Conclusion

In this way we can use a WCF service as a Model for our MVC application.

Login to add your contents and source code to this article
share this article :
post comment
 

Thanks for using this services

Posted by Arjun Panwar Jan 27, 2012
Team Foundation Server Hosting
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Team Foundation Server Hosting
Become a Sponsor