Update Database On CheckBox Change (Checked/Unchecked) Using jQuery and Ajax

This article explains how to populate (bind) CheckBox in GridView from the  database in ASP.NET using jQuery and Ajax. Also this article explains how to save the CheckBox checked (selected) value to the database.
 
Background
  1. VS2013
  2. C#
  3. SQL Server

Database

I have used the following table with schema as follows.
 
  
  1. CREATE TABLE [dbo].[ReportData]
  2. (    
  3.     [id] [int] IDENTITY(1,1) NOT NULL,    
  4.     [RName] [nvarchar](50) NULL,    
  5.     [RDescripation] [nvarchar](50) NULL,    
  6.     [Status] [bitNULL,    
  7. CONSTRAINT [PK_ReportData] PRIMARY KEY CLUSTERED     
  8. (    
  9.     [id] ASC    
  10. )
  11. WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ONON [PRIMARY]    
  12. ON [PRIMARY]    
HTML Markup
 
Here I have used jQuery DataTable plugin for displaying data instead of ASP.NET server control GridView as it provides a broad range of facilities (sorting, searching, pagination) and it is very optimized. You can know more about jQuery DataTable from the following link.
  1. <form id="form1" runat="server">  
  2.     <div class="col-lg-offset-4 col-md-8">  
  3.         <h1>New Example</h1>  
  4.     </div>  
  5.     <br />  
  6.     <table id="example" class="table table-hover table-striped table-bordered table-responsive">  
  7.         <thead>  
  8.             <tr>  
  9.                 <th>Id</th>  
  10.                 <th>Report Name</th>  
  11.                 <th>Report Description</th>  
  12.                 <th>Status</th>  
  13.                 <th>  
  14.                     <label id="lbltext1">Update Status</label>  
  15.                 </th>  
  16.             </tr>  
  17.         </thead>  
  18.         <tbody><% for (var data = 0; data < TableData.Rows.Count; data++)    
  19.                   { %>  
  20.             <tr>  
  21.                 <td><%=TableData.Rows[data]["id"]%>  
  22.                 </td>  
  23.                 <td><%=TableData.Rows[data]["RName"]%>  
  24.                 </td>  
  25.                 <td><%=TableData.Rows[data]["RDescripation"]%>  
  26.                 </td>  
  27.                 <td><%=TableData.Rows[data]["Status"]%>  
  28.                 </td>  
  29.                 <td><%if (TableData.Rows[data][3].ToString() == "True")    
  30.                          { %>  
  31.                     <input type="checkbox" class="chcktbl1" checked="checked" name="chcktbl1" data-id="  
  32.                         <%=TableData.Rows[data]["id"]%>/><%} %><%else    
  33.                          { %>  
  34.                         <input type="checkbox" class="chcktbl1" name="chcktbl1" data-id="  
  35.                             <%=TableData.Rows[data]["id"]%>/><%} %>  
  36.                         </td>  
  37.                     </tr><% } %>  
  38.                 </tbody>  
  39.             </table>  
  40.         </form>    
TableData is the public DataTable with namespace System.Data.DataTable from code behind in .cs page.
 
Binding Data 

The following query fills data in DataTable from which we are binding data in our jQuery DataTable.
  1. public DataTable TableData = new DataTable();  
  2.         public static string Constr = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;  
  3.         protected void Page_Load(object sender, EventArgs e)  
  4.         {  
  5.             if (!IsPostBack)  
  6.             {  
  7.                 GetAllData();  
  8.             }  
  9.         }  
  10.         private void GetAllData() //Get all the data and bind it in HTLM Table       
  11.         {  
  12.             using (var con = new SqlConnection(Constr))  
  13.             {  
  14.                 const string query = "select * from ReportData order by id desc";  
  15.                 using (var cmd = new SqlCommand(query, con))  
  16.                 {  
  17.                     using (var sda = new SqlDataAdapter())  
  18.                     {  
  19.                         cmd.Connection = con;  
  20.                         sda.SelectCommand = cmd;  
  21.                         using (TableData)  
  22.                         {  
  23.                             TableData.Clear();  
  24.                             sda.Fill(TableData);  
  25.                         }  
  26.                     }  
  27.                 }  
  28.             }  
  29.         } 
Scripts
 
The following is the jQuery code and reference to bind data in jQuery DataTable.
  1. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>  
  2.  <script src="js/jquery.dataTables.min.js"></script>  
  3.  <script type="text/javascript">  
  4.      $(document).ready(function () {  
  5.          $('#example').DataTable({  
  6.          });  
  7.      });  
  8.  </script> 
After this point the page will look as per the following image:
 
 
Updating CheckBox value to the Database
 
The following is my jQuery which makes Ajax call for updating checkbox event.
  1. <script type="text/javascript">  
  2.         $(".chcktbl1").click(function () {  
  3.             var rdata = $(this).attr("data-id"); // reading the id of the checkbox through data-id   
  4.             console.log(rdata);  
  5.             //alert(rdata);  
  6.             $.ajax({  
  7.                 type: "Post",  
  8.                 contentType: "application/json; charset=utf-8",  
  9.                 url: "GridUpdate.aspx/UpdateIsData",  
  10.                 data: '{eid: ' + rdata + '}',  
  11.                 dataType: "json",  
  12.                 success: function (response) {  
  13.                     if (response != 0) {  
  14.                         alert("Data Update Successfully!!!!");  
  15.                         location.reload();  
  16.                     }  
  17.                 },  
  18.                 error: function (response) {  
  19.                     if (response != 1) {  
  20.                         alert("Error!!!!");  
  21.                     }  
  22.                 }  
  23.             });  
  24.         });  
  25.     </script> 
On success I am using location.reload(); to reload the page to show the reflected changes in Grid, instead of this you can use Append if you don't want to load your page.
 
The following is the code used to update checkbox event in database. As I have done this using Ajax call so it has to be a WebMethod.
  1. [WebMethod]  
  2. public static void UpdateIsData(int eid)  
  3. {  
  4.     if (eid != null)  
  5.     {  
  6.         try  
  7.         {  
  8.             string data = string.Empty;  
  9.             var con = new SqlConnection(Constr);  
  10.             // Chenge Staus For check  
  11.             var q = "Select status from ReportData Where id='" + eid + "'";  
  12.             var command = new SqlCommand(q, con);  
  13.             con.Open();  
  14.             SqlDataReader readData = command.ExecuteReader();  
  15.             while (readData.Read())  
  16.             {  
  17.                 data = readData["status"].ToString();  
  18.                 con.Close();  
  19.                 if (data == "False")  
  20.                 {  
  21.                     using (var con2 = new SqlConnection(Constr))  
  22.                     {  
  23.                         var query = "update ReportData set Status='True' where id='" + eid + "'";  
  24.                         con2.Open();  
  25.                         var cmd = new SqlCommand(query, con2);  
  26.                         cmd.ExecuteNonQuery();  
  27.                         con2.Close();  
  28.                     }  
  29.                 }  
  30.                 else  
  31.                 {  
  32.                     using (var con1 = new SqlConnection(Constr))  
  33.                     {  
  34.                         var query = "update ReportData set Status='False' where id='" + eid + "'";  
  35.                         con1.Open();  
  36.                         var cmd = new SqlCommand(query, con1);  
  37.                         cmd.ExecuteNonQuery();  
  38.                         con1.Close();  
  39.                     }  
  40.                 }  
  41.             }  
  42.         }  
  43.         catch (Exception)  
  44.         {  
  45.         }  
  46.     }  

You can download the attached sample project and use as per your requirement.
 
Hope that helps and thanks for reading.