Save data using asp.net web services and jquery ajax

Step 1 : Create Insert Stored Procedure 
 
Create procedure spInsertEmployee
@Name nvarchar(50),
@Gender nvarchar(10),
@Salary int
as
Begin
     Insert into tblEmployee
     values (@Name, @Gender, @Salary)
End
 
Step 2 : Modify EmployeeService.asmx.cs as shown below 
 
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
using System.Web.Services;
 
namespace Demo
{
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [System.Web.Script.Services.ScriptService]
    public class EmployeeService : System.Web.Services.WebService
    {
        [WebMethod]
        public void AddEmployee(Employee emp)
        {
            string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            {
                SqlCommand cmd = new SqlCommand("spInsertEmployee", con);
                cmd.CommandType = CommandType.StoredProcedure;
 
                cmd.Parameters.Add(new SqlParameter()
                {
                    ParameterName = "@Name",
                    Value = emp.Name
                });
 
                cmd.Parameters.Add(new SqlParameter()
                {
                    ParameterName = "@Gender",
                    Value = emp.Gender
                });
 
                cmd.Parameters.Add(new SqlParameter()
                {
                    ParameterName = "@Salary",
                    Value = emp.Salary
                });
 
                con.Open();
                cmd.ExecuteNonQuery();
            }
        }
 
        [WebMethod]
        public void GetAllEmployees()
        {
            List<Employee> listEmployees = new List<Employee>();
 
            string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
            using (SqlConnection con = new SqlConnection(cs))
            {
                SqlCommand cmd = new SqlCommand("Select * from tblEmployee", con);
                con.Open();
                SqlDataReader rdr = cmd.ExecuteReader();
                while (rdr.Read())
                {
                    Employee employee = new Employee();
                    employee.ID = Convert.ToInt32(rdr["Id"]);
                    employee.Name = rdr["Name"].ToString();
                    employee.Gender = rdr["Gender"].ToString();
                    employee.Salary = Convert.ToInt32(rdr["Salary"]);
                    listEmployees.Add(employee);
                }
            }
 
            JavaScriptSerializer js = new JavaScriptSerializer();
            Context.Response.Write(js.Serialize(listEmployees));
        }
    }
}
 
Step 3 : Modify HtmlPage1.html as shown below.
 
<html>
<head>
    <script src="jquery-1.11.2.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            $('#btnAddEmployee').click(function () {
                var employee = {};
                employee.Name = $('#txtName').val();
                employee.Gender = $('#txtGender').val();
                employee.Salary = $('#txtSalary').val();
 
                $.ajax({
                    url: 'EmployeeService.asmx/AddEmployee',
                    method: 'post',
                    data: '{emp: ' + JSON.stringify(employee) + '}',
                    contentType: "application/json; charset=utf-8",
                    success: function () {
                        getAllEmployees();
                    },
                    error: function (err) {
                        alert(err);
                    }
                });
            });
 
            function getAllEmployees() {
                $.ajax({
                    url: 'EmployeeService.asmx/GetAllEmployees',
                    dataType: "json",
                    method: 'post',
                    success: function (data) {
                        var employeeTable = $('#tblEmployee tbody');
                        employeeTable.empty();
 
                        $(data).each(function (index, emp) {
                            employeeTable.append('<tr><td>' + emp.ID + '</td><td>'
                                + emp.Name + '</td><td>' + emp.Gender
                                + '</td><td>' + emp.Salary + '</td></tr>');
                        });
                    },
                    error: function (err) {
                        alert(err);
                    }
                });
            }
        });
    </script>
</head>
<body style="font-family:Arial">
    <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>
        <tr>
            <td colspan="2">
                <input type="button" id="btnAddEmployee" value="Add Employee" />
            </td>
        </tr>
    </table>
    <br />
    <table id="tblEmployee" border="1" style="border-collapse:collapse">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Gender</th>
                <th>Salary</th>
            </tr>
        </thead>
        <tbody></tbody>
    </table>
</body>
</html>

Comments

Popular posts from this blog

Automatically send Birthday email using C#.Net

Drag and Drop multiple File upload using jQuery AJAX in ASP.Net using C# and VB.Net

Difference between each and map in jquery