CRUD Operations Using Ajax - Part 1

Introduction

This is a simple CRUD operation using Ajax or without loading the page and binding the data in HTML Table using Ajax.

Description

To implement this first we need to create a table in our database. The table structure I have used is like the following:



The SQL query for creating the table is as follows:

  1. CREATE TABLE [dbo].[TblUser](    
  2.     [EmpId] [int] IDENTITY(1,1) NOT NULL,    
  3.     [Fname] [nvarchar](30) NOT NULL,    
  4.     [Mname] [nvarchar](30) NULL,    
  5.     [Lname] [nvarchar](30) NULL,    
  6.     [Gender] [nchar](10) NOT NULL,    
  7.     [EMail] [nvarchar](50) NOT NULL,    
  8.     [DOB] [nvarchar](30) NOT NULL,    
  9.     [MaritalStatus] [nvarchar](30) NOT NULL,    
  10.     [Hobbies] [nvarchar](30) NULL,    
  11.     [Telephone] [nvarchar](30) NULL,    
  12.     [Mobile] [nvarchar](30) NULL,    
  13.     [Address] [nvarchar](300) NOT NULL,    
  14.     [PinCode] [nvarchar](30) NOT NULL,    
  15.     [State] [nvarchar](30) NOT NULL,    
  16.     [Nationality] [nvarchar](30) NOT NULL,    
  17.     [DOJ] [nvarchar](30) NULL,    
  18.     [CreatedDate] [datetime] NOT NULL,    
  19.     [ModifiedDate] [datetime] NOT NULL,    
  20.  CONSTRAINT [PK_TblUser] PRIMARY KEY CLUSTERED     
  21. (    
  22.     [EmpId] ASC    
  23. )WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ONON [PRIMARY]    
  24. ON [PRIMARY]   
Design

Here I have used HTML controls instead of ASP.NET Server controls and also used Bootstrap Template for better view.

The main reason I prefer HTML controls instead of ASP.NET server controls is that they are lightweight and validation can be managed by client side. But still there are a lot of advantageS of server controls (eg. Maintaining view state, events and many more.).
  1. <div class="col-lg-8">  
  2.     <div class="panel panel-primary">  
  3.         <div class="panel-heading">  
  4.             <h3 class="panel-title"><i class="fa fa-bar-chart-o"></i>Employee Details </h3>  
  5.         </div>  
  6.         <div class="panel-body">  
  7.             <div class="form-group col-lg-4">  
  8.                 <label>First Name</label>  
  9.                 <input type="text" name="FirstName" id="FirstName" class="form-control" placeholder="First Name" required="" />  
  10.             </div>  
  11.             <div class="form-group col-lg-4">  
  12.                 <label>Middle Name</label>  
  13.                 <input type="text" name="MiddleName" id="MiddleName" class="form-control" placeholder="Kumar" required="" />  
  14.             </div>  
  15.             <div class="form-group col-lg-4 ">  
  16.                 <label>Surname</label>  
  17.                 <input type="text" name="Surname" id="Surname" class="form-control" placeholder="Gupta" required="" />  
  18.             </div>  
  19.             <div class="clearfix"></div>  
  20.             <div class="form-group col-lg-6">  
  21.                 <label>Email ID</label>  
  22.                 <input type="email" name="EmailId" id="EmailId" class="form-control" placeholder="[email protected]" required="" />  
  23.             </div>  
  24.             <div class="form-group col-lg-6">  
  25.                 <label>Date of Birth </label>  
  26.                 <input type="date" name="Dob" id="Dob" min="1920-01-02" class="form-control datepicker" required="" />  
  27.             </div>  
  28.             <div class="form-group col-lg-6">  
  29.                 <label>MaritalStatus</label>  
  30.                 <select name="MaritalStatus" id="MaritalStatus" class="form-control" required="">  
  31.                     <option value="" disabled="disabled">-- Select -- </option>  
  32.                     <option value="Single">Single</option>  
  33.                     <option value="Married">Married</option>  
  34.                 </select>  
  35.             </div>  
  36.             <div class="form-group col-lg-6">  
  37.                 <label>Hobbies</label>  
  38.                 <input type="text" name="Hobbies" id="Hobbies" class="form-control" placeholder="Football, Cricket etc." />  
  39.             </div>  
  40.   
  41.             <div class="form-group col-lg-6">  
  42.                 <label>Home Telephone</label>  
  43.                 <input type="text" name="TelephoneNo" id="TelephoneNo" class="form-control" placeholder="1234567890" />  
  44.             </div>  
  45.   
  46.             <div class="form-group col-lg-6">  
  47.                 <label>Mobile</label>  
  48.                 <input type="tel" name="MobileNo" id="MobileNo" class="form-control" required="" placeholder="0987654321" />  
  49.             </div>  
  50.             <div class="form-group col-lg-12">  
  51.                 <label>Residential Address</label>  
  52.                 <textarea rows="2" name="ResidentialAddress" id="ResidentialAddress" class="form-control" required="">  
  53.                     <div class="form-group col-lg-6 ">  
  54.                         <label>Pin Code</label>  
  55.                         <input name="PinCode" id="PinCode" class="form-control" placeholder="999999" type="text">  
  56.                     </div>  
  57.   
  58.                     <div class="form-group col-lg-6">  
  59.                         <label>State</label>  
  60.                         <select name="State" id="State" class="form-control" required="">  
  61.                             <option value="" disabled="disabled">-- Select -- </option>  
  62.                             <option value="Maharashtra">Maharastra</option>  
  63.                             <option value="Assam">Assam</option>  
  64.                             <option value="UP">UP</option>  
  65.                             <option value="Gujarat">Gujarat</option>  
  66.                             <option value="AP">Andhra Pradesh</option>  
  67.                         </select>  
  68.                     </div>  
  69.                     <div class="form-group col-lg-6">  
  70.                         <label>Nationality</label>  
  71.                         <input name="title" id="Nationality" class="form-control" placeholder="Indian" type="text">  
  72.                     </div>  
  73.                     <div class="form-group col-lg-6">  
  74.                         <label>Date of Joining</label>  
  75.                         <input name="Doj" id="Doj" class="form-control datepicker" required="" type="date">  
  76.                     </div>  
  77.                     <div class="form-group col-lg-8">  
  78.                         <div style="float: right">  
  79.                             <input value="Cancel" id="BtnCancel" class="btn btn-primary" type="button">  
  80.                             <input class="btn btn-primary" name="submitButton" id="btnSave" value="Save" type="button">  
  81.                         </div>  
  82.                     </div>  
  83.             </div>  
  84.         </div>  
  85.     </div>  
  86. </div> 
And the form will somehow look like the following:



Now we need to do Ajax insert for all the fields, that's why I have taken class for all the fields and my class is like this:

Employee Class
  1. public class Employee  
  2. {  
  3.    public int EmpId;  
  4.    public string FName;  
  5.    public string LName;  
  6.    public string MName;  
  7.    public string Email;  
  8.    public DateTime Dob;  
  9.    public string MaritalStatus;  
  10.    public string Hobbies;  
  11.    public string HomeMobile;  
  12.    public string OfficeMobile;  
  13.    public string Address;  
  14.    public string Pincode;  
  15.    public string State;  
  16.    public string Nationality;  
  17.    public DateTime Doj;  
  18.    public DateTime CreatedDateTime;  
  19.    public DateTime ModifiedDateTime;  

Save Method to Insert Data in the Database

As we need to call the method through Ajax, so it has to be  WebMethod and static:
  1. [WebMethod]  
  2. public static void SaveUser(Employee objEmployee) //Insert data in database  
  3. {  
  4.     using (var con = new SqlConnection(Constr))  
  5.     {  
  6.         using (var cmd = new SqlCommand("INSERT INTO TblUser VALUES(@Fname, @Mname,@Lname,@Email,@Dob,@MStatus,@Hobbies,"+
  7.                    "@HMobile,@OMobile,@Address,@Pin,@State,@Nationality,@Doj,@CreatedDate,@ModifiedDate)"))  
  8.         {  
  9.             cmd.CommandType = CommandType.Text;  
  10.             cmd.Parameters.AddWithValue("@Fname", objEmployee.FName);  
  11.             cmd.Parameters.AddWithValue("@Mname", objEmployee.MName);  
  12.             cmd.Parameters.AddWithValue("@Lname", objEmployee.LName);  
  13.             cmd.Parameters.AddWithValue("@Email", objEmployee.Email);  
  14.             cmd.Parameters.AddWithValue("@Dob", objEmployee.Dob);  
  15.             cmd.Parameters.AddWithValue("@MStatus", objEmployee.MaritalStatus);  
  16.             cmd.Parameters.AddWithValue("@Hobbies", objEmployee.Hobbies);  
  17.             cmd.Parameters.AddWithValue("@OMobile", objEmployee.OfficeMobile);  
  18.             cmd.Parameters.AddWithValue("@HMobile", objEmployee.HomeMobile);  
  19.             cmd.Parameters.AddWithValue("@Address", objEmployee.Address);  
  20.             cmd.Parameters.AddWithValue("@Pin", objEmployee.Pincode);  
  21.             cmd.Parameters.AddWithValue("@State", objEmployee.State);  
  22.             cmd.Parameters.AddWithValue("@Nationality", objEmployee.Nationality);  
  23.             cmd.Parameters.AddWithValue("@Doj", objEmployee.Doj);  
  24.             cmd.Parameters.AddWithValue("@CreatedDate",DateTime.Now);  
  25.             cmd.Parameters.AddWithValue("@ModifiedDate", DateTime.Now);  
  26.             cmd.Connection = con;  
  27.             con.Open();  
  28.             cmd.ExecuteNonQuery();  
  29.             con.Close();  
  30.         }  
  31.     }  

Now we need to call the method SaveUser() through Ajax to save data in the database.
  1. <script type="text/javascript">  
  2.     $(function() {  
  3.         $("#btnSave").click(function() {  
  4.             var user = {};  
  5.             user.FName = $("#FirstName").val(); // FName as per name of Employee Class  
  6.             user.LName = $("#Surname").val();  
  7.             user.MName = $("#MiddleName").val();  
  8.             user.Gender = $("#Male").val();  
  9.             user.Email = $("#EmailId").val();  
  10.             user.Dob = $("#Dob").val();  
  11.             user.MaritalStatus = $("#MaritalStatus").val();  
  12.             user.Hobbies = $("#Hobbies").val();  
  13.             user.HomeMobile = $("#TelephoneNo").val();  
  14.             user.OfficeMobile = $("#MobileNo").val();  
  15.             user.Address = $("#ResidentialAddress").val();  
  16.             user.Pincode = $("#PinCode").val();  
  17.             user.State = $("#State").val();  
  18.             user.Nationality = $("#Nationality").val();  
  19.             user.Doj = $("#Doj").val();  
  20.             user.CreatedDateTime = new Date();  
  21.             user.ModifiedDateTime = new Date();  
  22.             $.ajax({  
  23.                 type: "POST",  
  24.                 url: "Default.aspx/SaveUser"// Default.aspx is the page and SaveUser is the WebMethod to save data in database  
  25.                 data: '{objEmployee: ' + JSON.stringify(user) + '}'//objEmployee is the object of Employee Class defined in .cs  
  26.                 dataType: "json",  
  27.                 contentType: "application/json; charset=utf-8",  
  28.                 success: function() {  
  29.                     alert("User has been added successfully.");  
  30.                     getDetails(); //This method is to bind the added data into my HTML Table through Ajax call instead of page load  
  31.                     // window.location.reload(); we can also use this to load window to show updated data  
  32.                 },  
  33.                 error: function() {  
  34.                     alert("Error while inserting data");  
  35.                 }  
  36.             });  
  37.             return false;  
  38.         });  
  39.     });  
  40. </script> 
After this point we have our inserted data in the database.

Display Data in Table Structure(like Grid View):
  1. <table id="dataTables-example" class="table table-striped table-bordered table-hover dataTable no-footer" role="grid" aria-describedby="dataTables-example_info">  
  2.     <thead>  
  3.         <tr role="row">  
  4.             <th class="sorting_asc" tabindex="0" aria-controls="dataTables-example" rowspan="1" colspan="1" style="width: 175px;" aria-sort="ascending" aria-label="Rendering engine: activate to sort column descending">Name</th>  
  5.             <th class="sorting" tabindex="0" aria-controls="dataTables-example" rowspan="1" colspan="1" style="width: 203px;" aria-label="Browser: activate to sort column ascending">Email Id</th>  
  6.             <th class="sorting" tabindex="0" aria-controls="dataTables-example" rowspan="1" colspan="1" style="width: 184px;" aria-label="Platform(s): activate to sort column ascending">Mobile(H)</th>  
  7.             <th class="sorting" tabindex="0" aria-controls="dataTables-example" rowspan="1" colspan="1" style="width: 150px;" aria-label="Engine version: activate to sort column ascending">Mobile(O)</th>  
  8.             <th class="sorting" tabindex="0" aria-controls="dataTables-example" rowspan="1" colspan="1" style="width: 108px;" aria-label="CSS grade: activate to sort column ascending">Joining Date</th>  
  9.             <th class="sorting" tabindex="0" aria-controls="dataTables-example" rowspan="1" colspan="1" style="width: 108px;" aria-label="CSS grade: activate to sort column ascending">Birth Date</th>  
  10.             <th class="sorting" tabindex="0" aria-controls="dataTables-example" rowspan="1" colspan="2" style="width: 108px;" aria-label="CSS grade: activate to sort column ascending">Action</th>  
  11.         </tr>  
  12.     </thead>  
  13.     <tbody>  
  14.         <% for (var data = 0; data < TableData.Rows.Count; data++)    
  15.                                                        { %>  
  16.             <tr class="gradeA odd" role="row">  
  17.                 <td class="sorting_1">  
  18.                     <%=TableData.Rows[data]["FName"]%>  
  19.                 </td>  
  20.                 <td>  
  21.                     <%=TableData.Rows[data]["EMail"]%>  
  22.                 </td>  
  23.                 <td>  
  24.                     <%=TableData.Rows[data]["Telephone"]%>  
  25.                 </td>  
  26.                 <td>  
  27.                     <%=TableData.Rows[data]["Mobile"]%>  
  28.                 </td>  
  29.                 <td>  
  30.                     <%=TableData.Rows[data]["DOJ"]%>  
  31.                 </td>  
  32.                 <td>  
  33.                     <%=TableData.Rows[data]["DOB"]%>  
  34.                 </td>  
  35.                 <td>  
  36.                     <input type="button" class="btn btn-primary editButton" data-id="<%=TableData.Rows[data][" EmpId "] %>" data-toggle="modal" data-target="#myModal" name="submitButton" id="btnEdit" value="Edit" />  
  37.                 </td>  
  38.                 <td>  
  39.                     <input type="button" class="btn btn-primary" name="submitButton" id="btnDelete" value="Delete" />  
  40.                 </td>  
  41.             </tr>  
  42.             <% } %>  
  43.     </tbody>  
  44. </table> 

Ajax Call to Show Data

  1. function getDetails() {  
  2.     $.ajax({  
  3.         type: "POST",  
  4.         contentType: "application/json; charset=utf-8",  
  5.         url: "Default.aspx/GetData"//Default.aspx is page and GetData is the WebMethod  
  6.         data: {},  
  7.         dataType: "json",  
  8.         success: function(data) {  
  9.             $('#dataTables-example tbody').remove(); // Every time I am removing the body of Table and applying loop to display data  
  10.             //console.log(data.d);    
  11.             for (var i = 0; i < data.d.length; i++) {  
  12.                 $("#dataTables-example").append(  
  13.                     "<tr><td>" + data.d[i].FName + "</td><td>" + data.d[i].Email + "</td>" +  
  14.                     "<td>" + data.d[i].HomeMobile + "</td>" + "<td>" + data.d[i].OfficeMobile + "</td>" +  
  15.                     "<td>" + data.d[i].Doj + "</td>" + "<td>" + data.d[i].Dob + "</td>" +  
  16.                     "<td>" + "<input type='button' class='btn btn-primary editButton' data-id='" + data.d[i].EmpId + "' data-toggle='modal' data-target='#myModal' name='submitButton' id='btnEdit' value='Edit' />" + "</td>" +  
  17.                     "<td><input type='button' class='btn btn-primary' name='submitButton' id='btnDelete' value='Delete'/> </td></tr>");  
  18.             }  
  19.         },  
  20.         error: function() {  
  21.             alert("Error while Showing update data");  
  22.         }  
  23.     });  

Note: We can use window.location.reload(); instead of getDetails(). But the getDetails() method will load the entire page to show the added data in the table.
 
WebMethod to Get Data to be binded to Table using Ajax call:
  1. [WebMethod]  
  2.    public static Employee[] GetData() //Show the details of the data after insert in HTML Table  
  3.    {  
  4.        var details = new List<Employee>();  
  5.        using (var con = new SqlConnection(Constr))  
  6.        {  
  7.            const string query = "select * from TblUser order by EmpId desc";  
  8.            using (var cmd = new SqlCommand(query, con))  
  9.            {  
  10.                using (var sda = new SqlDataAdapter())  
  11.                {  
  12.                    cmd.Connection = con;  
  13.                    sda.SelectCommand = cmd;  
  14.                    TableData.Clear();  
  15.                    sda.Fill(TableData);  
  16.                    details.AddRange(from DataRow dtrow in TableData.Rows  
  17.                        select new Employee  
  18.                        {  
  19.                            EmpId = Convert.ToInt32(dtrow["EmpId"]),  
  20.                            FName = dtrow["Fname"].ToString(),  
  21.                            Email = dtrow["EMail"].ToString(),  
  22.                            HomeMobile = dtrow["Telephone"].ToString(),  
  23.                            OfficeMobile = dtrow["Mobile"].ToString(),  
  24.                            Doj = dtrow["DOJ"].ToString(),  
  25.                            Dob = dtrow["DOB"].ToString()  
  26.                        });  
  27.                }  
  28.            }  
  29.        }  
  30.        return details.ToArray();  
  31.    } 
Method to Show data on Load:
  1. protected void Page_Load(object sender, EventArgs e)    
  2. {    
  3.     if (!IsPostBack)    
  4.     {    
  5.         GetAllData();    
  6.     }    
  7. }    
  8. private void GetAllData() //Get all the data and bind it in HTLM Table     
  9. {    
  10.     using (var con = new SqlConnection(Constr))    
  11.     {    
  12.         const string query = "select * from TblUser order by EmpId desc";    
  13.         using (var cmd = new SqlCommand(query, con))    
  14.         {    
  15.             using (var sda = new SqlDataAdapter())    
  16.             {    
  17.                 cmd.Connection = con;    
  18.                 sda.SelectCommand = cmd;    
  19.                 using (TableData)    
  20.                 {    
  21.                     TableData.Clear();    
  22.                     sda.Fill(TableData);    
  23.                 }    
  24.             }    
  25.         }    
  26.     }    
  27. }   
After adding this the page will look like the following:

 
For PopUp Edit and Delete in HTML Table through Ajax Visit Crud Operations Ajax Part-2.
You will get complete attached CRUD Application in Part-2.

For Inserting multiple rows in the database from HTML table visit here.

Hope that helps, thanks for reading.
 

Up Next
    Ebook Download
    View all
    Learn
    View all