Saturday, February 28, 2015

Consuming WCF Service USING jquery/ajax

First, we need to Add New Service as shown below.





Click on Add Button







Iservice.cs





using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;

// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService" in both code and config file together.
[ServiceContract]
public interface IService
{
    [OperationContract]
    void DoWork();

    [OperationContract]
    [System.ServiceModel.Web.WebInvoke(Method = "POST",
        ResponseFormat = System.ServiceModel.Web.WebMessageFormat.Json)]
    string GetEmployees(string result);

}


Service.cs









[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service : IService
    {
        public void DoWork()
        {
        }

        public string GetEmployees(string result)
        {
            List<object> emp = new List<object>();
            SqlConnection con = new SqlConnection();
            con.ConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "select Firstname,Lastname from emp where " +
            "Firstname like @result + '%'";
            cmd.Parameters.AddWithValue("@result", result);
            cmd.Connection = con;
            con.Open();
            SqlDataReader dr = cmd.ExecuteReader();
            while (dr.Read())
            {
                emp.Add(new
                        {
                            FirstName = dr["Firstname"],
                            Lastname = dr["Lastname"]
                        });
            }
            con.Close();
            return (new JavaScriptSerializer().Serialize(emp));
        }

    }


Now, the service is ready. and we need to consume the service.

Now, add new form and design the form as shown below

<body>
    <form id="form1" runat="server">
        <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <input id="btnsearch" type="button" value="Search" />
        <div id="results"></div>
    </form>

</body>

web.config

  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior name="ServiceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="true"/>
        </behavior>
      </serviceBehaviors>
      <endpointBehaviors>
        <behavior name="ServiceAspNetAjaxBehavior">
          <enableWebScript />
        </behavior>
      </endpointBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"/>
    <services>
      <service behaviorConfiguration="ServiceBehavior" name="Service">
        <endpoint address="" binding="webHttpBinding" contract="IService" behaviorConfiguration="ServiceAspNetAjaxBehavior">
          <identity>
            <dns value="localhost"/>
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>
      </service>
    </services>
  </system.serviceModel>


Javascript Code:

    <script src="jquery-1.7.min.js"></script>
    <script type="text/javascript">
        $("#btnsearch").live("click", function () {
            $.ajax({
                type: "POST",
                contentType: "application/json; charset=utf-8",
                url: '<%=ResolveUrl("~/Service.svc/GetEmployees") %>',
                data: '{"result": "' + $("#TextBox1").val() + '"}',
                processData: false,
                dataType: "json",
                success: function (response) {
                    var employees = eval(response.d);
                  
                    var html = "";
                    $.each(customers, function () {
                        html += "<span>FirstName: " + this.FirstName + " Lastname: " + this.Lastname + "</span><br />";
                    });
                    $("#results").html(html == "" ? "No Records Found" : html);
                },
                error: function (a, b, c) {
                    alert(a.responseText);
                }
            });
        });

    </script>


Here ResolveUrl : will get the application folder Name

Output:




No comments:

Post a Comment

Thank you for visiting my blog

Kubernetes

Prerequisites We assume anyone who wants to understand Kubernetes should have an understating of how the Docker works, how the Docker images...