Sharing Business entity between Client (JavaScript) and Web Server by Using ASP.NET AJAX Web Service

 In the new era of Web 2.0, it is very important to update content in client browser, without page refresh.ASP.NET AJAX is very helpful to do above task.

 To make developer life simple, asp.net Ajax has feature by which entity object can be shared between client browser and web server. There is no need to create array and pass to web service method as parameter.

Let’s have an example as listing below:

STEP 1: Create two projects WebService (i.e. Web Application) and ExposeByService (i.e. Class Library)

                                                    Projects

Add Employee Class in ExposeByService project. Copy below code into that class:

namespace ExposeByService

{

    public  class Employee

    {

        public Employee()

        {

        }

 

       //automatic prpperties

        public int EmpNumber { get; set; }

        public string EmployeeName { get; set; }

 

      

    }

}

STEP 2. Execute the following substeps:

a.  Add webservice in WebService project.

b.   To allow Web Service to be called from script, using ASP.NET AJAX, uncomment System.Web.Script.Services.ScriptService] WebService calss attribute.

c.  To Expose entity object add [System.Web.Script.Services.GenerateScriptType(typeof(ExposeByService.Employee))] attribute to WebService Class.

d.  Add HelloEmployee Test method in webservice:

 

    [WebMethod]

 public ExposeByService.Employee HelloEmployee(ExposeByService.Employee emp)

    {       

        return emp;

  

 }

 

 

 

STEP 3. Execute the following substeps:

a.  Add Default.aspx page in WebSercice Project

b.  Add ScripManager and Service Reference as give in below code

    <asp:ScriptManager ID=”ScriptManager1″ runat=”server” >

    <Services>

    <asp:ServiceReference Path=”~/WebService.asmx” />

    </Services>

    </asp:ScriptManager>

c.  Add Javascript code in Javascript tag:

 

    <script type=”text/jscript” language=”jscript”>

        function CallEmployeeClass() {

 

            //crete object of employee class

            var obj = new ExposeByService.Employee();

            obj.EmpNumber = 123;

            obj.EmployeeName = “Ghajani”;

          //Call HelloEmployee Method

            WebService.HelloEmployee(obj, onReturn,onError);

           

        }

        function onReturn(result) {

          //If you check result here ,it will show EmpNumber and EmployeeName

// as asigned in CallEmployeeClass function.

          

        }

        function onError(result) {

//if you assign empNumber other then Integer

//it will trough dtatype conversion  error without server trip

          

        }

    </script>

 

To test above example, call CallEmployeeClass function from HTML control as common practice.

 Ref:

http://www.asp.net/learn/Ajax/tutorial-05-cs.aspx

Thanks for Reading

Rukhsar Ahmad

Tagged: , ,

Leave a comment