JSON ASP.NET Web Services with jQuery

using System;

using System.Web;

using System.Web.Services;

using System.Web.Services.Protocols;

using System.Web.Script.Services;

using System.Collections.Generic;

using System.Linq;

public class Employee

{

public string firstname;

public string lastname;

public int age;

}

///

/// Summary description for Employeeservice

///

[WebService(Namespace = “http://tempuri.org/”)]

[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

[ScriptService]

public class Employeeservice : WebService

{

List Employees = new List{

new Employee{firstname=”Aamir”,lastname=”Hasan”,age=20},
new Employee{firstname=”awais”,lastname=”Hasan”,age=50},
new Employee{firstname=”Bill”,lastname=”Hasan”,age=70},
new Employee{firstname=”sobia”,lastname=”khan”,age=80},

};

[WebMethod]

public List GetAllEmployees()

{

return Employees;

}

[WebMethod]

public List GetEmployeesByDoors(int doors)

{

var query = from c in Employees

where c.Doors == doors

select c;

return query.ToList();

}

}

All that’s needed now is some Javascript for the getEmployees() method that has been assigned to the onclick event of the html button. This will go into the section of the page:

$(function() {

$(‘#Button1’).click(getEmployees);

});

function getEmployees() {

$.ajax({

type: “POST”,

url: “Employeeservice.asmx/GetAllEmployees”,

data: “{}”,

contentType: “application/json; charset=utf-8”,

dataType: “json”,

success: function(response) {

var Employees = (typeof response.d) == ‘string’ ? eval(‘(‘ + response.d + ‘)’) : response.d;

$(‘#output’).empty();

for (var i = 0; i < Employees.length; i++) {

$('#output').append('

‘ + Employees[i].lastname + ‘ ‘ +

Employees[i].firstname + ‘
Age: ‘ +

Employees[i].age + ‘
Doors: ‘ +

‘);

}

},

failure: function(msg) {

$(‘#output’).text(msg);

}

});

}

Share