I am Raghuveer

In my opinion programming means thinking, and it is fun. My vision is to teach programming in more understandable manner to the students from rural background. I support programming for everyone

Showing posts with label AJAX. Show all posts
Showing posts with label AJAX. Show all posts

Using JQuery, AJAX, JSON and ASP.NET Web Services

Due to the latest paradigm shift in web development, more and more websites are loading and displaying all types of dynamic contents on the web pages. Web 2.0 based websites such as Gmail. Facebook and Twitter have not only changed the user’s expectations but also forced developers to learn more dynamic and exciting ways to build web applications. Client side web technologies like AJAX, XHTML, DOM, JavaScript and JQuery are now mandatory ingredients of every web developer resume. In my previous tutorial, I have shown you how you can call ASP.NET web services using JQuery AJAX capabilities. In this tutorial, I will show you how you can pass parameters to web services and how you can use JSON data returned from web services to display dynamic contents on web page.

Due to the latest paradigm shift in web development, more and more websites are loading and displaying all types of dynamic contents on the web pages. Web 2.0 based websites such as Gmail. Facebook and Twitter have not only changed the user’s expectations but also forced developers to learn more dynamic and exciting ways to build web applications. Client side web technologies like AJAX, XHTML, DOM, JavaScript and JQuery are now mandatory ingredients of every web developer resume. In my previous tutorial, I have shown you how you can call ASP.NET web services using JQuery AJAX capabilities. In this tutorial, I will show you how you can pass parameters to web services and how you can use JSON data returned from web services to display dynamic contents on web page.

Create a new ASP.NET website in the visual studio and add following Employee.cs class in App_Code folder of your project. I will be using this class from the web service to return the list of Employee class objects to the clients.

public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Salary { get; set; }
}


Next, add an ASP.NET web service EmployeeWebService.asmx in the project by using Add New Item dialog box. The complete web service code is shown below:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class EmployeeWebService : System.Web.Services.WebService {
List<Employee> list = new List<Employee>();
public EmployeeWebService () {
//Uncomment the following line if using designed components
//InitializeComponent();
list.Add(new Employee { Id = 1, Name = "Peter", Salary = 22000 });
list.Add(new Employee { Id = 2, Name = "Mark", Salary = 24000 });
list.Add(new Employee { Id = 3, Name = "James", Salary = 28000 });
list.Add(new Employee { Id = 4, Name = "Simon", Salary = 29000 });
list.Add(new Employee { Id = 5, Name = "David", Salary = 19000 });

}
[WebMethod]
public List<Employee> GetAllEmployees() {
return list;
}

[WebMethod]
public Employee GetEmployeeDetails(string employeeId)
{
int empId = Int32.Parse(employeeId);
Employee emp = list.Single( e => e.Id == empId);
return emp;
}

}

In start, the web service declares a list of Employee objects which I will be using to store employee objects for this tutorial.

List<Employee> list = new List<Employee>();


I have added five employee objects to the list in the constructor of the web service. I am using this approach only for simplifying this tutorial as in a real world application these records are normally stored in the database.

list.Add(new Employee { Id = 1, Name = "Peter", Salary = 22000 });
list.Add(new Employee { Id = 2, Name = "Mark", Salary = 24000 });
list.Add(new Employee { Id = 3, Name = "James", Salary = 28000 });
list.Add(new Employee { Id = 4, Name = "Simon", Salary = 29000 });
list.Add(new Employee { Id = 5, Name = "David", Salary = 19000 });

A web method GetAllEmployees returns the list of employees to the clients.

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


Another simple web method GetEmployeeDetails will filter and return a single Employee object based on employee id.

[WebMethod]
public Employee GetEmployeeDetails(string employeeId)
{
int empId = Int32.Parse(employeeId);
Employee emp = list.Single( e => e.Id == empId);
return emp;
}


Next add the following code in your web page in HTML source. It has a DropDownList to display all employees and an HTML table to display single employee details.

<form id="form1" runat="server">
Select Employee:
<asp:DropDownList ID="DropDownList1" runat="server" Width="150">
<asp:ListItem Text="Select" Value="-1" />
</asp:DropDownList>

<br />
<br />
<table style="border: solid 1px black; width: 300px; display: none; background-color: #f3f3f3"
cellpadding="4" cellspacing="0" id="outputTable">
<tr>
<td>Employee ID:</td>
<td><span id="spnEmployeeId" /></td>
</tr>
<tr>
<td>Employee Name:</td>
<td><span id="spnEmployeeName" /></td>
</tr>
<tr>
<td>Salary:</td>
<td><span id="spnSalary" /></td>
</tr>
</table>
</form>

Before staring JQuery AJAX code make sure you have JQuery file available in the scripts folder of your website, and you have added file reference in the page <head> element.
<script src="scripts/jquery-1.4.3.min.js" type="text/javascript"></script>
Next add a JavaScript code block and typical JQuery ready function to get things started when the document is ready and DOM tree is loaded by the browser. The first statement is a call to another JavaScript function GetAllEmployees which is declared just after ready function. This function will call GetAllEmployees web service method, and then it will populate the DropDownList control from the JSON data returned from the web service method. Next the DropDownList change event function handler is defined, which first gets the selected employee id from theDropDownList using JQuery val method and then pass that employee id to another JavaScript function GetEmlployeeDetails which will retrieve details of that particular employee by calling web service GetEmployeeDetails method and then will display details in HTML table.

<script type="text/javascript">
$(document).ready(function () {
// Load Employees
GetAllEmployees();
var DropDownList1 = $("#DropDownList1");
DropDownList1.change(function (e) {
var employeeId = DropDownList1.val();
if (employeeId != -1) {
// Get Employee Details
GetEmployeeDetails(employeeId);
} else {
$("#outputTable").hide();
}
});
});
function GetAllEmployees() {
// JQuery AJAX Code Here
}
function GetEmployeeDetails(employeeId) {
// JQuery AJAX Code Here
}

</script>


As you can see in the above code, I didn’t define the GetAllEmployees and GetEmployeeDetails functions so that you can focus on ready function implementation and can understand more easily what is going on in JQuery ready function. To complete this tutorial, I need to show you the code required inside the above two functions to call web services methods and to update controls and user interface elements. Following is the implementation of GetAllEmployees function:

function GetAllEmployees()
{
var DropDownList1 = $("#DropDownList1");
$.ajax({
type: "POST",
url: "EmployeeWebService.asmx/GetAllEmployees",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var Employees = response.d;
$.each(Employees, function (index, employee) {
DropDownList1.append('<option value="' + employee.Id + '">' + employee.Name + '</option>');
});

},
failure: function (msg) {
alert(msg);
}
});
}


In the above code snippet, JQuery ajax() method is used to send AJAX request to ASP.NET web service method GetAllEmployees. From the parameters, you can easily guess the service method url, request type (POST) and data type (JSON). If you are not familiar with the ajax()method parameters, I will recommend you to read my tutorial Calling ASP.NET Web Services using JQuery AJAX for more detailed understanding of the ajax() method and JSON.
Inside the success function handler of ajax() method, I have used JQuery each() method to loop through all the employees I received in JSON response (response.d) and I appended the HTML elements inside DropDownList to display all employees. If you will build and test your page in the browser you will see DropDownList populate with employee names as shown in the following figure. You can also see the JSON response inFireBug just below to the DropDownList.

JQuery AJAX JSON Response

The following is the code required for the GetEmployeeDetails function. The code is almost similar to the GetAllEmployees function as it is also using JQuery ajax() method to call web service method but there are two differences. First, I am passing employee id as a parameter in JSON format using the data option of JQuery ajax() method. Second, inside success method I am not using any loop to iterate employees as there is only one employee to receive from the web service method. Note the Employee class properties Id, Name and Salary are used to display values inside span elements declared in HTML table above.

function GetEmployeeDetails(employeeId)
{
$.ajax({
type: "POST",
url: "EmployeeWebService.asmx/GetEmployeeDetails",
data: "{'employeeId':'" + employeeId + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response)
{
var Employee = response.d;
$("#spnEmployeeId").html(Employee.Id);
$("#spnEmployeeName").html(Employee.Name);
$("#spnSalary").html(Employee.Salary);
$("#outputTable").show();

},
failure: function (msg)
{
alert(msg);
}
});
}

That’s all we need to call web service methods using JQuery AJAX and to display single or multiple records coming from web service method in JSON format. Build and run your web page, and you will see output similar to following figure:

JQuery AJAX JSON Response

 

Download Source Code Download Source Code Live Demo Live Demo

Using ASP.NET AJAX ModelPopupExtender from Server Side

AJAX Model Popup Extender

Create a new web site in Visual Studio and open the page in which you want to use ModelPopupExtender control. The first thing you need to add is a CSS class which I will attach with ModelPopupExtender control to make page background transparent and darker when theModelPopupExtender control will appear on screen. So add this CSS in your page header tag.

<style type="text/css">
.BackgroundStyle
{
background-color: #f3f3f3;
filter: alpha(opacity=50);
opacity: 0.5;
}
</style>


Next, we are moving to our page and you need to add ScriptManager control first which is required to use any ASP.NET AJAX related feature on the page.
<asp:ScriptManager ID="ScriptManager1" runat="server" />
Next you need to add ASP.NET AJAX UpdatePanel control on the page. This control is required to perform AJAX based asynchronous post backs so that when user click submit button inside model dialog box the whole page does not need to be reloaded.

<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>

</ContentTemplate>
</asp:UpdatePanel>

Next add a button and a label control inside the ContentTemplate of the UpdatePanel. The button will ask user to participate in a quick poll which will be shown in model dialog box and when user will submit the poll by clicking the submit button inside model dialog I will show the results on the label control.

<asp:Button ID="Button1" runat="server" Text="Quick Poll" />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
Next you need to add a Panel control inside the ContentTemplate of the UpdatePanel which will be used as a popup window by theModelPopupExtender control.
<asp:Panel ID="Panel1" runat="server" BackColor="#ffffff"
BorderColor="#dadada" BorderStyle="Solid" BorderWidth="4px"
Height="190px" Width="350px" Font-Names="Arial" Font-Size="10pt">
<table cellpadding="10" cellspacing="0" style="width: 100%">
<tr>
<td>
What is your Favorite Programming Language?
</td>
</tr>
<tr>
<td>
<asp:RadioButtonList ID="RadioButtonList1" runat="server">
<asp:ListItem>Java</asp:ListItem>
<asp:ListItem>VB.NET</asp:ListItem>
<asp:ListItem>C#</asp:ListItem>
</asp:RadioButtonList>
</td>
</tr>
<tr>
<td>
<asp:Button ID="Button2" runat="server" Text="Submit"
OnClick="Button2_Click" />
<asp:Button ID="Button3" runat="server" Text="Cancel" />
</td>
</tr>
</table>
</asp:Panel>


The above markup inside Panel control is very straight forward. It has a RadioButtonList control and two buttons arranged inside the html table for better layout. Notice that the submit button has OnClick event handler attached with it which will be defined in code behind file of the page.
Finally, you need to add the ASP.NET AJAX ModelPopupExtender control inside the ContentTemplate of the UpdatePanel control as follows:

<ajax:ModalPopupExtender ID="ModalPopupExtender1" runat="server"
PopupControlID="Panel1"
DropShadow="True"
TargetControlID="Button1"
CancelControlID="Button3"
BackgroundCssClass="BackgroundStyle" />

The following section explains all the ModelPopupExtender properties in detail:
TargetControlID: This property needs the id of the target control that will activate the model popup dialog box. I have given the id of the first button control “Button1”.
PopupControlID: This property needs the id of the control you want to use as a popup window. I have given the reference of the Panel control which ModelPopupExtender will display on screen.
DropShadow: A Boolean property to add drop shadow to the popup window. I set it to true and you can see a black shadow with popup window in the figure above.
OkControlID: This property needs the id of the control which will dismiss the model popup dialog box. I am not using this property in this tutorial because I want to handle submit button click event on the server side.
CancelControlID: This property needs the id of the control that will cancel or dismiss the popup dialog box.
OnOkScript: This property needs the name of the JavaScript function that will be called automatically when the modal popup is dismissed with the OkControlID. You don’t need to set this property if you want to handle submit button click in the server side code with a post back.
OnCancelScript: This property needs the name of the JavaScript function that will be called automatically when modal popup is dismissed with the CancelControlID. In the example above I haven’t used this property because I don’t want to run any script on Cancel button click.
BackgroundCssClass: This property needs the name of the CSS class to apply to the page background when the modal popup is displayed. I have given the name of the CSS class we defined in the start.
PopupDragHandleControlID: This property needs the ID of the control which will be used to drag the popup dialog box on screen. Normally, this control is available at the top of the popup window and acts as a title bar for dragging operation. I have not used this property in this tutorial but you can provide dragging feature by setting this property in your applications.
X: This property can be used to position the model dialog box on screen horizontally by setting the X coordinate of the top/left corner of the modal popup. If you will skip this property the model dialog box will appear centered horizontally.
Y: This property can be used to position the model dialog box on screen vertically by setting the Y coordinate of the top/left corner of the modal popup. If you will skip this property the model dialog box will appear centered vertically.
RepositionMode: This property determines whether the popup needs to be repositioned when the window is resized or the page is scrolled by the user.
In the end, add the following code in the page code behind file to handle Submit button click event. That’s it, Test your page in the browser and you will see the model dialog box similar to the above figure. Select any language option from the model dialog box and click submit button. You will notice the label on the page updated with your selected language without a full post back.

protected void Button2_Click(object sender, EventArgs e)
{
Label1.Text = RadioButtonList1.SelectedItem.Text;
}

Calling Web Services in Client Script using ASP.NET AJAX

Web Services play an important role in data transport and communication between the client the server. Web services reside on the server and wait to be called by any client and most of the time these clients are written in server side technologies such as ASP.NET, PHP or JSP etc. ASP.NET AJAX provides web developers ability to call web services from the client side language such as JavaScript asynchronously to improve the user experience and to avoid full page refresh and postback. In this tutorial, I will show you how you can call an ASP.NET web service with the help of ASP.NET AJAX.

For the purpose of this tutorial I have created a web service with the name ProductsService.asmx. If you are new to web services and don’t know how to add web service right click on your website name in Solution Explorer and click Add New Item option and select the Web Service icon from the available file templates as shown in figure below. A new file with the name ProductsService.asmx will be added in your website and the code behind file for the web service will be added in App_Code folder.

Add ASP.NET Web Service

Notice the ProductsService class is derived from the System.Web.Services.WebService class available in .NET Framework class library. Also check the following directive in your code and make sure it is not commented because this directive is required to call web service using ASP.NET AJAX.[System.Web.Script.Services.ScriptService]
The implementation of web service is fairly straight forward. It has only one method GetProducts which is decorated with [WebMethod] attribute that is required to expose web service methods to consumers and calling applications. The method takes category id as a parameter and return some products based on the category. I am returning hard coded products names and not connecting database in this tutorial but you can easily write code to return products from the database.

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

[System.Web.Script.Services.ScriptService]
public class ProductsService : System.Web.Services.WebService
{
[WebMethod]
public List<string> GetProducts(int categoryId)
{
List<string> list = new List<string>();
if (categoryId == 1)
{
list.Add("Nokia N95");
list.Add("Nokia N70");
list.Add("Nokia 6630");
}
else
{
list.Add("Dell Laptop");
list.Add("HP Laptop");
list.Add("Sony Laptop");
}
return list;
}
}


To consume web service by using client script you need to add an instance of the ASP.NET AJAX ScriptManager control in your page. This control supports a Services collection which can be used to add the reference of web services you want to call from client side JavaScript. The ASP.NET AJAX asynchronous communication layer automatically generates JavaScript proxy classes for each Web service reference you add usingScriptManager control.
Once your page is requested, the proxy class is downloaded to the browser at the page load time and provides a client object that represents the exposed methods of a Web service. To call a method of the Web service, you can call corresponding method of generated proxy class. The proxy class in turn communicates with the Web service asynchronously by using XmlHttpObject of the browser.
For this tutorial, I have added the reference of ProductsService.asmx by using <asp:ScriptReference> element inside Services collection under the <asp:ScriptManager> element. The remaining form has a DropDownList, an HTML button and a Label control. Notice that the onclick event of the Button1 control is calling a JavaScript function Button1_onclick() which needs to be defined in the JavaScript in your page.

<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/ProductsService.asmx" />
</Services>
</asp:ScriptManager>

Select Category:
<asp:DropDownList ID="DropDownList1" runat="server">
<asp:ListItem Value="1">Mobiles</asp:ListItem>
<asp:ListItem Value="2">Laptops</asp:ListItem>
</asp:DropDownList>
<input id="Button1" type="button" value="Get Products"
onclick="Button1_onclick()" />
<br />
<br />
<asp:Label ID="Label1" runat="server"></asp:Label>
</form>


As I mentioned earlier that calling a Web service method from client script is asynchronous means the communication will take place behind the scene and user will remain interactive with the page. If your web service returns some data you must provide a callback function you want to execute on successful call to web service. You can also provide another callback function to handle errors in case the Web service call failed due to any communication or server error or Web service return no data.
I have added the following JavaScript code in my page to call Web service. Notice how I have called the GetProducts method of the Web service using the ProductsService proxy class generated automatically for me when I have added the Web service reference using ScriptManagercontrol. Also notice the callback functions onSuccess and onFailed have been passed as a second and third parameter in the proxy class GetProducts method to receive the results or error messages returned by the Web service and to update the page accordingly.

<head runat="server">
<title>Consuming Web Services From AJAX</title>
<script type="text/javascript">
function Button1_onclick()
{
var categoryId = $get("DropDownList1").value;
ProductsService.GetProducts(categoryId, onSuccess, onFailed);
}
function onSuccess(result)
{
var Label1 = $get("Label1");
Label1.innerHTML = "";
for(i=0 ; i<result.length ; i++)
{
Label1.innerHTML += result[i] + "<br />";
}
}
function onFailed(error)
{
var Label1 = $get("Label1");
Label1.innerHTML = "Service Error: " + error.get_message();
}
</script>
</head>


Build your project and test your page in the browser and you will see output similar to the following when you will click the button after selecting a category from the DropDownList.

ASP.NET AJAX Web Service