JQuery POST & GET Request to WCF Service in ASP.Net MVC

 

In this tutorial we see how to call a WCF Rest Service from ASP.Net MVC Application using JQuery.

Lets get started –

================================================================================================

STEP # 1 – Create MVC 2 Project

================================================================================================

1) Open VS 2010. File –> New –> Project –> Select ASP.Net MVC2 Web Application Template. Give name as “JQueryCallToWcf”.

JQueryWCF1

2) Click OK. VS prompts you to add Test Project for the Application, Select NO.

JQueryWCF2

3) Click OK.

================================================================================================

STEP # 2 – Modify Views/Home/Index.aspx

================================================================================================

 

Place the following code in the Index.aspx –

<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Home Page
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <h2><%: ViewData["Message"] %></h2>
    <p>
        To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.<p>

        <strong>Enter Registration Details</strong>

        <p>

            Enter User Name - 

                <input 
                    type="text" 
                    id="txtuserName" /><br />

            Enter User Email - 

                <input 
                    type="text" 
                    id="txtuserEmail" /><br />

        </p>
            <a 
                href="#" 
                class="btnSubmit">
                Submit
            </a>
            
            <br /><br />

        <strong>Enter User Name to Retrieve</strong>
        
        <p>

            Enter User Name - 

                <input 
                    type="text" 
                    id="find" />
        </p>
            <a 
                href="#" 
                class="btnRetrieve">
                Retrieve
            </a>
        
        <div 
            id="DisplayResult">
        </div>

    </p>
</asp:Content>

================================================================================================

STEP # 3 – Add WCF Service

================================================================================================

1) Right Click Solution –> Add –> New Item –> Select “AJAX Enables WCF Service” –> Give name as “UserService”.

image

 

Add the following code to the UserService.svc.cs –

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;

namespace JQueryCallToWcf
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(
        RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class UserService
    {
            // Create a List of User type and add temporary data. This List will be used a 
            // Fake Repository for Data Tranasaction. In real world we can replace this with 
            // EntityFramework or Linq2Sql Data Model for actual data transactions.

            public static List<User> lstUsers = new List<User>()
            {
                new User() { Name="Rami", Email="Rami@Rami.com"},
                new User() { Name="Bill", Email="Bill@Bill.com"},
                new User() { Name="Mark", Email="Mark@Mark.com"},
            };


            // We have two service methods - SetUser and GetUser, which sets and gets 
            // user from fake repository.

            [OperationContract]
            [WebInvoke(
                BodyStyle = WebMessageBodyStyle.WrappedRequest, 
                RequestFormat = WebMessageFormat.Json, 
                ResponseFormat = WebMessageFormat.Json)]
            public void SetUser(string usertype, string email)
            {
                lstUsers.Add(new User() { Name = usertype, Email = email });
            }

            [OperationContract]
            [WebGet(
                ResponseFormat = WebMessageFormat.Json)]
            public User GetUser(string name)
            {
                User op = lstUsers.Where(p => p.Name == name).FirstOrDefault();
                return op;
            }
        }

        // This is the User Class, holding properties for Name and email.

        [DataContract]
        public class User
        {
            [DataMember]
            public string Name { get; set; }

            [DataMember]
            public string Email { get; set; }
        }
}

================================================================================================

STEP # 4 – Add JQuery Script

================================================================================================

1) Right Click Scripts folder, then select Add –> New Item –> Select JScript File –> Give name as “UserServiceCalls.js”

image

2) Place the following code in that UserServiceCalls.js –

$(document).ready(function () {
    $(".btnSubmit").click(function () {
        $.ajax({
            cache: false,
            async: true,
            type: "POST",
            dataType: "json",
            url: "http://localhost:6037/UserService.svc/SetUser",
            data: '{ "usertype": "' + $("#txtuserName").val() + '", "email" : "' + $("#txtuserEmail").val() + '" }',
            contentType: "application/json;charset=utf-8",
            success: function (r) { alert("Successfully Registered!!!"); },
            error: function (e) { alert(e.statusText); }
        });
    });
    $(".btnRetrieve").click(function () {
        $.ajax({
            cache: false,
            async: true,
            type: "GET",
            dataType: "json",
            url: "http://localhost:6037/UserService.svc/GetUser",
            data: { name: $("#find").val() }, 
            contentType: "application/json;charset=utf-8",
            success: function (r) { if (r!= null) $("#DisplayResult").html(r.Email); },
            error: function (e) { alert(e.statusText); }
        });
    });
});

The only thing pending to make use of these JQuery Functions is to include our JQuery Script files in our Master Page –

1) Go to Site.Master file in Views/Shared folder. Paste the following code.

    <script src="../../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
    <script src="../../Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
    <script src="../../Scripts/UserServiceCall.js" type="text/javascript"></script>

================================================================================================

Explanation

================================================================================================

This Demo application is a simple one. We have a ASP.Net MVC Webform, it only consists of html Controls. We have a simple Registration form, which takes User Name and User Email. Once We client the Submit Hyperlink, JQuery will make a POST request to the WCF Service, which will add the data to our Users List.

To retrieve the data, we have a simple Html Text Input, in which we fill the User Name. Once we give the input and click Retrieve Link, JQuery makes a GET Request to WCF Service, which searches the List of users and send back the Data to browser. We Display result in the Div tag.

================================================================================================

Folder Structure

================================================================================================

JQueryWcfFolderStructure

================================================================================================

Demo

================================================================================================

Unable to display content. Adobe Flash is required.

Disclaimer:

All coding and suggestions made in the above discussion is strictly in point of view of the author. It is neither mentioned any where nor even concluded that this is the only possible way to go with, as there will be always a chance for a new approach in achieving the same requirement (in context of programming). The above mentioned code is strictly written and explained for the sake of new comers to C# and ASP.NET world. Read Complete Disclaimer in About page.

You may also like...

3 Pingbacks/Trackbacks

  • Pingback: JQuery POST & GET Request to WCF Service in ASP.Net MVC | Neorack Tutorials()

  • Pingback: Webmaster Crap » Blog Archive » JQuery POST & GET Request to WCF Service in ASP.Net MVC | Rami Vemula()

  • Pingback: Generics Get Class | More More Pics()

  • Jim

    Great article.

    ‘1) Right Click Solution –> Add –> New Item –> Select “AJAX Enables WCF Service”’ should be ‘1) Right Click PROJECT…’

  • JOSH

    EXCELLENT POST !!!!..

  • Chakri

    HI,
    Thanks for posting this kind of information,But i need to fetch the data from EDM by making use of wcf service from that service called from the Jquery,How can i achieve the task.

    Thanks
    Chakri

  • suresh

    Good

  • RamiVemula

    @Chakri – Please post your question in forums.asp.net.

  • Carlos

    Hi, its a good explanation but, when im using the jscript file from the svc file returns the email, but it doesnt show in the div tag :S …any suggestion?

    Sorry for my bad english.
    Thanks

  • RamiVemula

    @Carlos – I am not sure I got your question well.

  • Mohammad

    Hi
    I think you have made an excellent article, unfortunately its almost impossible to search for your article using google or bing.

  • Bilal

    Hi
    I’m experiencing same problem as @Carlos
    The get part does not work.
    When I enter e.g. Bill I expect to have Bills email address returned and placed on the div. However it never get placed on the div. I can see that it does get returned by the webservice, however it never displays on the div.

  • RamiVemula

    @Bilal – Check your Div Name. I replicated my code and it is working for me. check your code and compare it with mine.