Monday, December 14, 2009

Pass Javascript value to server side object & Event

Hi Friends

Its is very tuff job to transfer any javascript object to server side (code behind) objects and event by javascript. but .NET Framework 4 make this job very easy you can now pass Javascript from Javascript to code behind file using Ajax.

Passing parameters as primitive type

The easiest and most common way to passing javascript object information to server side method is Send it as individual parameters to the sever side method, please check below code show how to call server side "AddPerson" method with 4 argument

<script language="javascript" type="text/javascript">

var p1 = new Person('Adday', 'Michel','New York', 28);

var a = 0;

function passvalue() {

JavaWebApps.PersonService.AddPerson(p1.firstName,p1.lastName,p1.City,customer.age,function (response) {

});

}

</script>


The Person JavaScript class is a simple class with four properties firstName, lastName,City and age.


function Person(firstName, lastName,City, age) {

this.firstName = firstName;
this.lastName = lastName;
this.City=City;
this.age = age;
}


And code for server side AddPerson Method code

[WebMethod]
public string IAddPerson(string firstName, string lastName, string City, int age) {

return "Person added";
}