Support us .Net Basics C# SQL ASP.NET ADO.NET MVC Slides C# Programs Subscribe Buy DVD

Calling aspx page method using jquery

Suggested Videos
Part 64 - Save data using asp.net web services and jquery ajax
Part 65 - Check if username exists in database with ajax
Part 66 - How to suggest available username



In this video we will discuss how to call server side aspx page method using jQuery AJAX. 



We will have a c# function in the code-behind file, the retrieves employee details by ID from the SQL Server database. We want to call this server side c# function using jquery and display the data as shown below.

Calling aspx page method using jquery

Step 1 : Create SQL Server table and insert employee data

Create table tblEmployee
(
     Id int primary key identity,
     Name nvarchar(50),
     Gender nvarchar(10),
     Salary int
)
GO

Insert into tblEmployee values ('Mark', 'Male', 50000)
Insert into tblEmployee values ('Sara', 'Female', 60000)
Insert into tblEmployee values ('John', 'Male', 45000)
Insert into tblEmployee values ('Pam', 'Female', 45000)
GO

Step 2 : Create a stored procedure to retrieve employee data by ID

Create procedure spGetEmployeeById
@Id int
as
Begin
 Select ID, Name, Gender, Salary
 from tblEmployee
 where ID = @Id
End

Step 3 : Create new asp.net web application project. Name it Demo. 


Step 4 : Include a connection string in the web.config file to your database.
<add name="DBCS"
     connectionString="server=.;database=SampleDB;integrated security=SSPI" />

Step 5 : Add a class file to the project. Name it Employee.cs. Copy and paste the following code.


namespace Demo
{
    public class Employee
    {
        public int ID { get; set; }
        public string Name { get; set; }
        public string Gender { get; set; }
        public int Salary { get; set; }
    }
}

Step 6 : Add a new WebForm. Name it WebForm.aspx. Copy and paste the following code in the code-behind page.


using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace Demo
{
    public partial class WebForm1 : System.Web.UI.Page
    {
        [System.Web.Services.WebMethod]
        public static Employee GetEmployeeById(int employeeId)
        {
            Employee employee = new Employee();

            string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            {
                SqlCommand cmd = new SqlCommand("spGetEmployeeById", con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.Add(new SqlParameter()
                {
                    ParameterName = "@Id",
                    Value = employeeId
                });
                con.Open();
                SqlDataReader rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    employee.ID = Convert.ToInt32(rdr["Id"]);
                    employee.Name = rdr["Name"].ToString();
                    employee.Gender = rdr["Gender"].ToString();
                    employee.Salary = Convert.ToInt32(rdr["Salary"]);
                }
            }

            return employee;
        }
    }
}

Step 7 : Copy and paste the following HTML and jQuery code in WebForm1.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs"
         Inherits="Demo.WebForm1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="jquery-1.11.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#btnGetEmployee').click(function () {
                var empId = $('#txtId').val();
                $.ajax({
                    url: 'WebForm1.aspx/GetEmployeeById',
                    method: 'post',
                    contentType: "application/json",
                    data: '{employeeId:' + empId + '}',
                    dataType: "json",
                    success: function (data) {
                        $('#txtName').val(data.d.Name);
                        $('#txtGender').val(data.d.Gender);
                        $('#txtSalary').val(data.d.Salary);
                    },
                    error: function (err) {
                        alert(err);
                    }
                });
            });
        });
    </script>
</head>
<body style="font-family: Arial">
    <form id="form1" runat="server">
        ID :
        <input id="txtId" type="text" style="width: 86px" />
        <input type="button" id="btnGetEmployee" value="Get Employee" />
        <br /><br />
        <table border="1" style="border-collapse: collapse">
            <tr>
                <td>Name</td>
                <td><input id="txtName" type="text" /></td>
            </tr>
            <tr>
                <td>Gender</td>
                <td><input id="txtGender" type="text" /></td>
            </tr>
            <tr>
                <td>Salary</td>
                <td><input id="txtSalary" type="text" /></td>
            </tr>
        </table>
    </form>
</body>
</html>

jQuery tutorial for beginners

8 comments:

  1. I am trying to perform this assignment, but i keep getting the error popup - The page at localhost:xxxx says [object XMLHTTPRequest]. Could you help me pls why I am getting this issue in all browsers?

    ReplyDelete
    Replies
    1. In your html file, make sure all of your $.ajax settings are right. If you renamed WebForm1.aspx to another file name, make sure you make this change.

      Delete
  2. I'm getting [Object Object] when I apply it on online server. Can anyone help with this matter?

    ReplyDelete
    Replies
    1. public static Employee GetEmployeeById(int employeeId) Check if the static is given.

      Delete
    2. I got the same error and I replaced WebForm1.aspx with GetEmployeeById67.aspx in the html file. I named my aspx file GetEmployeeById67.aspx. Kudvenkat names his WebForm1.aspx.

      Delete
  3. how to load datetime from database to textbox datepicker. i'm load is ok but is error format
    ex /Date(1474441200000)/

    ReplyDelete
  4. How create in this example "Calling aspx page method using jquery" with Handling json data returned from asp.net web method?

    I try to add the following code, but I can not make it work. Is it an idea to have?

    [WebMethod] //opcion2
    public void GetEmployeeByIdv2(int employeeId)
    {
    Employee employee = new Employee();

    string cs = ConfigurationManager.ConnectionStrings["TestJquery"].ConnectionString;
    using (SqlConnection con = new SqlConnection(cs))
    {
    SqlCommand cmd = new SqlCommand("spGetEmployeeById", con);
    cmd.CommandType = CommandType.StoredProcedure;
    cmd.Parameters.Add(new SqlParameter()
    {
    ParameterName = "@Id",
    Value = employeeId
    });
    con.Open();
    SqlDataReader rdr = cmd.ExecuteReader();
    while (rdr.Read())
    {
    employee.ID = Convert.ToInt32(rdr["Id"]);
    employee.Name = rdr["Name"].ToString();
    employee.Gender = rdr["Gender"].ToString();
    employee.Salary = Convert.ToInt32(rdr["Salary"]);
    }
    }
    string resultado = "";
    JavaScriptSerializer js = new JavaScriptSerializer();
    // return js.Serialize(employee);
    resultado = Convert.ToString(js.Serialize(employee));
    }

    And Jquery


    //Part 67 video
    $(document).ready(function () {
    $('#btnGetEmployee2').click(function () {
    var empId = $('#txtId').val();
    $.ajax({
    method: 'post',
    url: 'EmployeeWebMethod.aspx/GetEmployeeByIdv2',

    data: '{employeeId:' + empId + '}',
    dataType: "json", //formato json
    success: function (data) {
    $('#txtName').val(data.d.Name);
    $('#txtGender').val(data.Gender);
    $('#txtSalary').val(data.Salary);
    },
    error: function (err) {
    alert(err);
    }
    });
    });
    });

    ReplyDelete
    Replies
    1. put in
      contentType: "application/json",
      with the other data passed in the json literal to the $.ajax method since you are passing hand made stringified data,data:'{employeeId'+empId+'}', to as the data property.

      Delete

If you like this website, please share with your friends on facebook and Google+ and recommend us on google using the g+1 button on the top right hand corner.