Return Multiple Values in Asp.Net Web Service and jQuery Ajax

← PrevNext →

In one of my previous posts, I have explained about Asp.Net Web Service, which dealt about Auto Completing textbox by extracting data from the database. Now in this article, I'll make the Web Service return multiple values with a single command. To make a call to the Web Methods, I am using jQuery Ajax functions.

As usual I'll use the Employee table to extract data and return the values to the client. All we need is to enter the ‘Name’ of the employee in a textbox control on the web page. Using the jQuery .blur() function, a call will be made to a Web Method

WebService.asmx

Open Solution Explorer and right click the project and select Add New Item… In the Item dialog box find and select Web Service and click the Add button. The WebService.asmx file will be added to the project which will be located at the root of your website.

We also need to configure the web.config file to avoid Internal Server Error (500).

The Markup followed by the Script
<head runat="server">
    <link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.1/jquery-ui.min.js"></script>
</head>

<body>
    <form id="form1" runat="server">
    <div>
         <%--ADD 1 TEXTBOX AND 3 LABELS.--%>
        <input type="text" id="tbEmpName" />
        
        <div><b>Designation:</b> <asp:Label ID="lblDesig" runat="server"></asp:Label></div>
        <div><b>Department:</b> <asp:Label ID="lblDept" runat="server"></asp:Label></div>
        <div><b>Date Of Joining:</b> <asp:Label ID="lblJOD" runat="server"></asp:Label></div>
    </div>
    </form>
</body>
The Script
<script>
    $(document).ready(function() {
       BindControls();
    });

    function BindControls() {
        $("#tbEmpName").blur(function() {
            $.ajax({
                url: "WebService.asmx/EmployeeDetails",
                data: "{ 'sName': '" + $('input[id=tbEmpName]').val() + "'}",
                dataType: "json",
                type: "POST",
                contentType: "application/json; charset=utf-8",
                success: function(data) {
                    if (data.d != '') {
                        $('span[id=lblDesig]').text(data.d.Designation);
                        $('span[id=lblDept]').text(data.d.Department);
                        $('span[id=lblJOD]').text(data.d.JoiningDate);
                    }
                }
            });
        });
    }
</script>
The Web Service (C#)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;

[WebService(Namespace = "https://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService {

    public class Employee {
        public string Designation;
        public string Department;
        public string JoiningDate;
    }

    [WebMethod]
    public Employee EmployeeDetails(string sName) {

        Employee objEmployee = new Employee();     // CREATE AN OBJECT.

        string sConnString = "Data Source=DNA;Persist Security Info=False;" +
            "Initial Catalog=DNA_CLASSIFIED;User Id=sa;Password=;Connect Timeout=30;";

        SqlConnection myConn = new SqlConnection(sConnString);
        SqlCommand objComm = new SqlCommand("SELECT *FROM Master_UserDetails " +
                        "WHERE FName LIKE '%'+@LookUP+'%'", myConn);
        myConn.Open();

        objComm.Parameters.AddWithValue("@LookUP", sName);
        SqlDataReader sdr = objComm.ExecuteReader();

        if (sdr.Read())
        {
            objEmployee.Designation = sdr["Designation"].ToString();
            objEmployee.Department = sdr["Department"].ToString();
            objEmployee.JoiningDate = sdr["JoiningDate"].ToString();
        }
        myConn.Close(); sdr.Close(); return objEmployee;
    }
}
(Vb.Net)
Imports System.Web
Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.Data.SqlClient

<System.Web.Script.Services.ScriptService()> _
<WebService(Namespace:="https://tempuri.org/")> _
<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Public Class WebService
    Inherits System.Web.Services.WebService

    Public Class Employee
        Public Designation As String
        Public Department As String
        Public JoiningDate As String
    End Class

    <WebMethod()> _
    Public Function EmployeeDetails(ByVal sName As String) As Employee
        Dim objEmployee As New Employee    ' CREATE AN OBJECT.

        Dim sConnString As String = "Data Source=DNA;Persist Security Info=False;" & _
            "Initial Catalog=DNA_CLASSIFIED;User Id=sa;Password=;Connect Timeout=30;"

        Dim myConn As New SqlConnection(sConnString)
        Dim objComm As New SqlCommand("SELECT *FROM Employee " & _
                "WHERE EmpName LIKE '%'+@LookUP+'%'", myConn)
        myConn.Open()

        objComm.Parameters.AddWithValue("@LookUP", sName)
        Dim sdr As SqlDataReader = objComm.ExecuteReader()

        If sdr.Read Then
            objEmployee.Designation = sdr("Designation").ToString()
            objEmployee.Department = sdr("Department").ToString()
            objEmployee.JoiningDate = sdr("JoiningDate").ToString()
        End If

        myConn.Close() : sdr.Close() : Return objEmployee
    End Function
End Class

In the WebService, I have declared a class called Employee, which encapsulates details like ‘designation’, ‘department’ and ‘joining date’ of the employee. An object of this class is created and values are assigned to its properties. Once data is extracted, the class object with the values is returned to the jQuery Ajax method.

← PreviousNext →