Saturday, February 12, 2011

Handling JSON Arrays returned from ASP.NET Web Services with jQuery

The Web Service methods that I will use revolve around cars. Having set up a web site in Visual Studio 2008, I have added a new item of type "Web Service" to the project, calling it EmpInfoService.asmx. The code-behind - EmpInfoService.cs - is automatically generated within the App_Code folder. The full code for that class file is as follows:

Code: asmx

public class Employee
{
public string FullName;
public string Designation;
public string PhoneNo;
}


/// <summary>
/// Summary description for Emp info
/// </summary>


[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]


[ScriptService]
public class EmpInfoService : WebService
{
List Employees = new List{
new Employee{FullName="Shakil",Designation="Manager",PhoneNo=5555454},
new Employee{FullName="Ahsan",Designation="Director",PhoneNo=4545454},
new Employee{FullName="Murhsed",Designation="Director",PhoneNo=5454545},
new Employee{FullName="Khurshid",Designation="Officer",PhoneNo=4545545},
new Employee{FullName="Abdul",Designation="Sr.Executive",PhoneNo=45454545},
new Employee{FullName="Yususf",Designation="Sr.Officer",PhoneNo=4545454545},
new Employee{FullName="Farid",Designation="Executive",PhoneNo=45454545},
new Employee{FullName="Munir",Designation="Executive",PhoneNo=454545454},
new Employee{FullName="Foyez",Designation="Executive",PhoneNo=45454545454}
};



[WebMethod]
public List GetAllEmployees()
{
return Employees;
}

[WebMethod]
public List GetEmployeesByName(string name)
{
var query = from c in Employees
where c.FullName == name
select c;
return query.ToList();
}
}


Code: ASPX

The mark-up in the aspx page that will call the Web Service is extremely simple:

<form id="form1" runat="server">
<input type="button" id="btnEmpId" value="Get Employe List" />
<div id="output"></div>
</form>



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 <head> section of the page:

First, jQuery is referenced via the src attribute of the first <script> tag. Then a click event is registered with the button which will invoke the getEmployees() function. After that is the getEmployees() function that is fired when the button is clicked.



Jquery:(Without parameter)

<script type="text/javascript" src="script/jquery-1.3.2.min.js"></script>
<script type="text/javascript">

$(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 = response.d;
$('#output').empty();
$.each(Employees, function(index, Employee) {
$('#output').append('<p><strong>' + Employee.FullName + ' <br />' +
Employee.Designation + '</strong><br /> Designation: ' +
Employee.PhoneNo + '<br />Phone: ' +'</p>');
});
},

failure: function(msg) {
$('#output').text(msg);
}
});
}
</script>


It makes use of the $.ajax(options) function within jQuery, and accepts an object with a number of optional properties.
type specifies the HTTP method, which in this case is POST.
url specifies the URL of the Web Service, together with the web method that is being called. This is followed by the parameters, which are applied to the data property.

In this case, no parameters are being passed, as we are calling the method that retrieves the entire collection of Employee.
The contentType and dataType MUST be specified.
Following this are two further functions: success defines what should be done if the call is successful, and failure handles exceptions that are returned.

In this case, the success callback is passed the resulting HTTP response. In response an object with a property - d - is returned, which contains an array of objects. Each object has a __type property which tells you that it is a Employee object, followed by the other properties of our Web Service Employee object.

The div with the id of output is emptied, in case there was clutter there from a previous ajax call. The jQuery each() function is used to iterate over the collection of objects. Each Employee object is accessed in turn, and its properties are written to a paragraph, which is then appended to the content of div output.

Now, share with you how to send parameter using jquery,
Here we want to filter employee info with employee name from DropDownList

<asp:DropDownList ID="ddlEmpName" runat="server">
<asp:ListItem>Shakil</asp:ListItem>
<asp:ListItem>Ahsan</asp:ListItem>
<asp:ListItem>Murshed</asp:ListItem>
<asp:ListItem>Farid</asp:ListItem>
</asp:DropDownList>

Jquery(with parameter see the bold):

<script type="text/javascript" src="script/jquery-1.3.2.min.js"></script>
<script type="text/javascript">

$(function() {
$('#Button1').click(getEmployees);
});


function getEmployees() {
$.ajax({
type: "POST",
url: "EmployeeService.asmx/GetEmployeesByName",
data: "{name: " + $('#<%= ddlEmpName.ClientID %>').val() + " }",

contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
var Employees = response.d;
$('#output').empty();
$.each(Employees, function(index, Employee) {
$('#output').append('<p><strong>' + Employee.FullName + ' <br />' +
Employee.Designation + '</strong><br /> Designation: ' +
Employee.PhoneNo + '<br />Phone: ' +'</p>');
});
},

failure: function(msg) {
$('#output').text(msg);
}
});
}
</script>

The url option now points to the appropriate method, and a parameter is passed into the data option, which uses jQuery syntax to reference the selected value from the DropDownList. I have used inline ASP.NET tags in this case to dynamically render the ID of the DropDownList using the ClientID property, so that there will be no issues in referencing the DropDownList if this code was transferred to a User Control or another control that implements INamingContainer.

All credits goes to Mr.Mikesdotnetting because I solved my problem from this superb article.

No comments:

Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'

Exception: Method 'StartWorkflowOnListItem' in type 'Microsoft.SharePoint.WorkflowServices.FabricWorkflowInstanceProvider'...