Friday, March 30, 2012

Using jQuery to Consume ASP.NET JSON Web Services

Using jQuery to Consume ASP.NET JSON Web Service:
 
Following are the steps for consume JSON webservice using JQuery.
  1. Add New Web Page JSONSaveDataWebservice.aspx
  2.  Add Web Service : wsEmployeeInsert.asmx
  3. Add  Java Script in aspx page.

JSONSaveDataWebservice.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="JSONSaveDataWebservice.aspx.cs"
    Inherits="JSONSaveDataWebservice" %>

DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>JSON SaveData Get Data Using Webservice Jquery title>
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js">script>
    <script src="Scripts/jquery-1.4.1.min.js" type="text/javascript">script>
    <script type="text/javascript" language="javascript">

        function CallService() {
            var name = $("#txtName").val();
            var age = $("#txtAge").val();
            $.ajax({
                type: "POST",
                url: "JSONSaveDataWebserviceaspx.aspx/InsertEmployee",
                data: "{'name':'" + name + "','age':'" + age + "'}",
                contentType: "application/json",
                async: false,
                success: function (data) {
                    alert("Sucess" + data.d);
                },
                error: function (data) { alert("Error" + data.d); }
            });
        }

        $(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() {
            var DropDownList1 = $("#DropDownList1");
            $.ajax({
                type: "POST",
                url: "wsEmployeeInsert.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(' + employee.Name + '');
                    });
                },
                failure: function (msg) {
                    alert(msg);
                }
            });
        }
        function GetEmployeeDetails(employeeId) {
            $.ajax({
                type: "POST",
                url: "wsEmployeeInsert.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);
                    $("#spnAddress").html(Employee.Address);
                    $("#spnSalary").html(Employee.Salary);
                    $("#outputTable").show();
                },
                failure: function (msg) {
                    alert(msg);
                }
            });
        }
    script>
head>
<body>
    <form id="form1" runat="server">
    <div>
        Name:
        <asp:TextBox ID="txtName" runat="server">asp:TextBox><br />
        Age:
        <asp:TextBox ID="txtAge" runat="server">asp:TextBox><br />
        <input id="_btnSubmit" type="button" value="Submit" onclick="CallService();" />
        <span id="message">span>
    div>
    <div>
        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>
                    Address:
                td>
                <td>
                    <span id="spnAddress" />
                td>
            tr>
            <tr>
                <td>
                    Salary:
                td>
                <td>
                    <span id="spnSalary" />
                td>
            tr>
        table>
    div>
    form>
body>
html>


JSONSaveDataWebservice.aspx.CS
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services; 
public partial class JSONSaveDataWebservice : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
    [WebMethod]
    public static string InsertEmployee(string name, int age)
    {
        string s_name = name;
        int s_age = age;
        return "Save Sucessfully";
    }
}

wsEmployeeInsert.asmx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

///


/// Summary description for wsEmployeeInsert
///

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class wsEmployeeInsert : System.Web.Services.WebService,IDisposable {
    List<Employee> list = new List<Employee>();
    public wsEmployeeInsert () {

        //Uncomment the following line if using designed components
        //InitializeComponent();
        list.Add(new Employee { Id = 1, Name = "Rajesh Tendulkar",Address="India", Salary = 10000 });
        list.Add(new Employee { Id = 2, Name = "Rahul Ganguly",Address="Asia", Salary = 20000 });
        list.Add(new Employee { Id = 3, Name = "Saurav Dravid",Address="China", Salary = 30000 });
        list.Add(new Employee { Id = 4, Name = "Suresh Sharma",Address="US", Salary = 40000 });
        list.Add(new Employee { Id = 5, Name = "Sachin Tiwari",Address="UK", Salary = 50000 });
    }

    [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;
    }   
}
partial  class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Addresses { get; set; }
    public decimal Salary { get; set; }
}


Notes:
  • Jquery
  • ASP.net
  • JSON
  • Web service

ShareThis

Welcome

Welcome to Rajesh Prajapati, asp.net blog.
Here you can find some useful code and information about asp.net., c#, VB.net, SQL Server, Web Service, Web Designing etc