Using ASP.Net C# class object in Javascript and Web Service

'DownloadDownload sample

Introduction

This sample demonstrates how you can use an an ordinary ASP.Net C# class instance as an object in Javascript. We can expose C# object to Javascript using web services. This sample first gets employee details from MS Access database using ADO.Net. Then use it to initiate Employee object and return it in a web method. Download attached sample and run it with Visual Studio 2010.

Sourcecode Explanation

  • Employee.cs contains declaration for Employee class.
  • EmployeeWebService.asmx.cs is a webservice file. It contains Web Methods that are used to initiate Employee object and return it.
    
        //Initiate connection string in constructoor
        public EmployeeWebService()
        {
            //Get server path for MS Access Database
            sDBPath = Server.MapPath(".") + @"\App_Data\MSAccessDB.mdb";
    
            //Use server path to build connection string for access database.
            ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + sDBPath + ";";
        }
    
        //Following method takes employee id as parameter and returns employee object from database.
        [WebMethod]
        public Employee GetOneEmployee(int EmployeeId)
        {
            //Write query to get employee using employee id
            OleDbDataAdapter ADAP = new OleDbDataAdapter("select * from Employees where EmployeeId=" + EmployeeId.ToString(), ConnectionString);
            DataSet DS = new DataSet();
            ADAP.Fill(DS);
            DataTable DTEmployees = DS.Tables[0];
    
            //Initiate Employee object using returned employee from database.
            Employee emp = new Employee();
            if (DTEmployees.Rows.Count > 0)
            {
                emp.EmployeeId = int.Parse(DTEmployees.Rows[0]["EmployeeId"].ToString());
                emp.EmployeeName = DTEmployees.Rows[0]["EmployeeName"].ToString();
            }
            return emp;
        }    
    
        //Following method gets all employees from database and returns them as ArrayList object.
        [WebMethod]
        public ArrayList GetAllEmployees()
        {
            ArrayList Employees = new ArrayList();
            OleDbDataAdapter ADAP = new OleDbDataAdapter("select * from Employees", ConnectionString);
            DataSet DS = new DataSet();
            ADAP.Fill(DS);
            DataTable DTEmployees = DS.Tables[0];
            for (int i = 0; i < DTEmployees.Rows.Count; i++)
            {
                Employee emp = new Employee();
                emp.EmployeeId = int.Parse(DTEmployees.Rows[i]["EmployeeId"].ToString());
                emp.EmployeeName = DTEmployees.Rows[i]["EmployeeName"].ToString();
                Employees.Add(emp);
            }
    
            return Employees;
        }
    
    
    
  • Above web methods are used in Javascript inside Default.aspx page source. In order to consume web service in Javascript, we need to add reference to web service in Default.aspx source.

        <asp:ScriptManager ID="ScriptManager1" runat="server">
        <Services>
            <asp:ServiceReference Path="EmployeeWebService.asmx" />
        </Services>
        </asp:ScriptManager>
    

  • Now call web service methods in Javascript code declared in Default.aspx.

    
            //Pass function name as parameter. This function will be called once web service call is finished.
            function GetAllEmployees() {
                EmployeeWebService.GetAllEmployees(GotAllEmployees);
            }
    
            //Pass function name as parameter. This function will be called once web service call is finished.
            function GetOneEmployee() {
                EmployeeWebService.GetOneEmployee(CurrentEmployee,GotOneEmployee);
            }
            
            //Once web service call is finished, following function fires and it returns employees as array of Employee class object.
            function GotAllEmployees(employees) {
                for (var i = 0; i < employees.length; i++) {
                    InsertEmployee(employees[i].EmployeeId, employees[i].EmployeeName);
                }
            }
    
            //Once web service call is finished, following function fires and it returns Employee class object.
            function GotOneEmployee(employee) {
                InsertEmployee(employee.EmployeeId, employee.EmployeeName);
                CurrentEmployee++;
    

Summary

Using web service methods combined with Javascript can be very powerful in developing feature rich web applications.